mercredi 30 août 2017

How to use java reflection to assign a generic instance's field with an object?

I'd like to write an util method to cast a json object to a kind of model.

public static <T> T getModelFromJson(Class<T> cls,JSONObject json)

And the part of the method is:

T model = cls.newInstance();
Field []fields = cls.getDeclaredFields();
for (Field field : fields) {
    Object o = json.get(field.getName());
    if(o == null){
        logger.error("no field:{}",field.getName());
    }
    //how to assign model's field with o
}

So....how to assign the model's field with Object o?





Aucun commentaire:

Enregistrer un commentaire