0

正如我在标题中提到的。这是我下面的代码


import java.lang.reflect.Field;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ObjectNode;

public class ReflectClass {

    public Double getDoubleKey() {
        return doubleKey;
    }

    public void setDoubleKey(Double doubleKey) {
        this.doubleKey = doubleKey;
    }

    public Long getLongKey() {
        return longKey;
    }

    public void setLongKey(Long longKey) {
        this.longKey = longKey;
    }

    private Double doubleKey;
    private Long longKey;

    public ReflectClass(JsonNode node) throws IllegalAccessException {
        Field[] fields = this.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (field.getType().equals(Double.class)) {
                field.setDouble(this, node.get(field.getName()).asDouble());
            } else if (field.getType().equals(Long.class)) {
                field.setLong(this, node.get(field.getName()).asLong());
            }
        }
    }

    public static void main(String[] args) throws IllegalAccessException {
        ObjectNode jNode = new ObjectMapper().createObjectNode();
        jNode.put("doubleKey", 1.0);
        jNode.put("longKey", 11L);
        new ReflectClass(jNode);

    }
}

但是,当我运行上面的代码时,会弹出如下错误。

java.lang.IllegalArgumentException: 无法将 java.lang.Double 字段 models.weibo.ReflectClass.doubleKey 设置为 (double)1.0

我当然可以通过传统方式初始化类实例,例如this.doubleKey = node.get("doubleKey").asDouble(). 但是,如果此类中有太多字段,我更愿意通过循环对其进行初始化。

4

0 回答 0