0

目标 :

set value for the given java bean at run time and generate JSON Object or JSON array.

以上是我的目标,我尝试了以下类似的方法:

package com.hexgen.tools;

import java.lang.reflect.Method;

import com.google.gson.Gson;

public class ConvertPOJOToJSON {
    public Object creatJSONObject(String className) throws IllegalArgumentException, IllegalAccessException, InstantiationException, Exception {
        Class<?> objectClass = null;
        Object clsObject =null;
        try {
            objectClass = Class.forName(className);
            clsObject = objectClass.newInstance();
             for(Method m : objectClass.getMethods())
                  if (m.getName().startsWith("set") && m.getParameterTypes().length == 1 && m.getModifiers()==23)
                     m.invoke(clsObject, "myValue");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return clsObject;
    }
public static void main(String[] args) {
    Gson gson = new Gson();
    ConvertPOJOToJSON pojoToJSON = new ConvertPOJOToJSON();
    try {
        System.out.println("JSON OBJECT : "+gson.toJson(pojoToJSON.creatJSONObject("com.hexgen.ro.request.CreateRequisitionRO")));
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

上述类的输出:

JSON OBJECT : {"isAllocable":false}

我给出的类中有很多字段,com.hexgen.ro.request.CreateRequisitionRO但只有一个布尔值设置为 false 并返回该值。

i have some constant value to set for the fields say if the field type is Integer than set some default integer value like so

编辑 :

我创建了一个如下所示的枚举:

包 com.hexgen.tools;

导入 java.math.BigDecimal;导入 java.math.BigInteger;导入 org.joda.time.LocalDate;

public enum DefaultParamValues {
    STRING("HEXGEN"),
    INTEGER(123),
    DATE(new LocalDate()),
    BOOLEAN(true),
    LONGVALUE(123123),
    BIGDECIMAL(new BigDecimal("100000"));

    private  String defaultString;
    private  int defaultInteger;
    private  LocalDate defaultDate;
    private  boolean defaultBoolean;
    private  long defaultLong;
    private  BigDecimal defaultBigDecimal;

    private DefaultParamValues(String strDefaultValue) {
        defaultString = strDefaultValue;
    }
    private DefaultParamValues(int intDefaultValue) {
        defaultInteger = intDefaultValue;
    }
    private DefaultParamValues(LocalDate dateDefaultValue) {
        defaultDate = dateDefaultValue;
    }
    private DefaultParamValues(boolean booleanDefaultValue) {
        defaultBoolean = booleanDefaultValue;
    }
    private DefaultParamValues(long longDefaultValue) {
        defaultLong = longDefaultValue;
    }
    private DefaultParamValues(BigDecimal bigIntegerDefaultValue) {
        defaultBigDecimal = bigIntegerDefaultValue;
    }
    public String getDefaultString() {
        return defaultString;
    }
    public int getDefaultInt() {
        return defaultInteger;
    }
    public LocalDate getDefaultDate() {
        return defaultDate;
    }

    public boolean getDefaultBoolean() {
        return defaultBoolean;
    }
    public long getDefaultLong() {
        return defaultLong;
    }
    public BigDecimal getDdefaultBigDecimal() {
        return defaultBigDecimal;
    }

}

创建了另一种方法,如下所示:

public Object creatObjectWithDefaultValue(String className) throws IllegalArgumentException, IllegalAccessException, InstantiationException {
        DefaultParamValues defaultParamValues = null;
        Class<?> objectClass = null;
        Object clsObject =null;
        try {
            objectClass = Class.forName(className);
            clsObject = objectClass.newInstance();
             Field[] fields = objectClass.getDeclaredFields();

             for(Field f:fields){
                  if(!f.isAccessible()){
                        f.setAccessible(true);
                        Class<?> type = f.getType();
                        if(! Modifier.isFinal(f.getModifiers()) && type.equals(Integer.class)){
                            f.set(clsObject, defaultParamValues.INTEGER);  
                        } else if( !Modifier.isFinal(f.getModifiers()) && type.equals(java.math.BigDecimal.class)){
                            f.set(clsObject, defaultParamValues.BIGDECIMAL);  
                        } else if(! Modifier.isFinal(f.getModifiers()) && type.equals(org.joda.time.LocalDate.class)){
                            f.set(clsObject,defaultParamValues.DATE);  
                        }  else if(! Modifier.isFinal(f.getModifiers()) && type.equals(boolean.class)){
                            f.set(clsObject, defaultParamValues.BOOLEAN);  
                        } else if(! Modifier.isFinal(f.getModifiers()) && type.equals(java.lang.String.class)){
                            f.set(clsObject, defaultParamValues.STRING);  
                        }
                        else if(! Modifier.isFinal(f.getModifiers()) && type.equals(long.class)){
                            f.set(clsObject, defaultParamValues.LONGVALUE);  

                        }
                       //f.setAccessible(false);
                     }

               }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return clsObject;
    }

设置默认值,但我得到以下异常:

Exception in thread "main" java.lang.IllegalArgumentException: Can not set java.math.BigDecimal field com.hexgen.ro.request.CreateRequisitionRO.transSrlNo to com.hexgen.tools.DefaultParamValues
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:146)
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:150)
    at sun.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:63)
    at java.lang.reflect.Field.set(Field.java:657)
    at com.hexgen.tools.JsonConverter.creatObjectWithDefaultValue(JsonConverter.java:93)
    at com.hexgen.tools.JsonConverter.main(JsonConverter.java:201)

请帮助我找到解决方案。

此致

4

1 回答 1

1

If your looking for a lightweight library which can do this and more including allowing you to do your own filtering to find Methods/Fields. I wrote an open source library which has no 3rd party dependencies and is available on Maven Central.

Checkout https://github.com/gondor/reflect

As for your issue it appears your setting the "Enum" constant and not the inner value of the enum. Wouldn't it DefaultParamValues.BIGDECIMAL.getDdefaultBigDecimal()

于 2013-04-30T05:24:31.667 回答