Java反射为java pojo设置Value

时间:2013-04-30 05:07:01

标签: java json reflection

目标:

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

编辑:

我创建了一个类似以下的枚举:

package com.hexgen.tools;

import java.math.BigDecimal; import java.math.BigInteger; import 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)

请帮我找到解决方案。

最好的问候

1 个答案:

答案 0 :(得分:1)

如果您正在寻找可以执行此操作的轻量级库,还包括允许您自己进行过滤以查找方法/字段。我写了一个没有第三方依赖关系的开源库,可以在Maven Central上找到。

结帐https://github.com/gondor/reflect

至于你的问题,看来你设置“枚举”常量而不是枚举的内部值。它不是DefaultParamValues.BIGDECIMAL.getDdefaultBigDecimal()