lundi 2 septembre 2019

Can't initialise a class instance from JsonNode with reflection

As I mentioned in the title. Here is my code below


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);

    }
}


However when I run the code above, the error like below pops up.

java.lang.IllegalArgumentException: Can not set java.lang.Double field models.weibo.ReflectClass.doubleKey to (double)1.0

I can certainly initialise the class instance by the traditional way like this.doubleKey = node.get("doubleKey").asDouble(). However if there are too many fields in this class, I'd prefer to initialise it through a loop.





Aucun commentaire:

Enregistrer un commentaire