lundi 12 septembre 2016

How to set a Field value as a plain Object via Reflection

I have a model class:

public class Model {

@KeyDefinition("name")
private String mName;

@KeyDefinition("age")
private int mAge;

public Model(){

}

And I have a List<Object>(Values) & a List<String> (Keys) that I handle through the map method:

public <T> T map(Class<T> cls){
    T instance;
    try {
        instance = cls.newInstance();
        for(Field field: cls.getDeclaredFields()){
            if(field.isAnnotationPresent(KeyDefinition.class)){
                KeyDefinition annotation = field.getAnnotation(KeyDefinition.class);
                for(int i = 0; i < mKeys.size(); i++){
                    if(annotation.value().equals(mKeys.get(i))){
                        field.setAccessible(true);
                        field.set(instance, mValues.get(i));
                    }
                }
            }
        }
    } catch (InstantiationException | IllegalAccessException e) {
        System.out.println(e.getMessage());
        return null;
    }
    return instance;
}

So if the value of the annotations is equals to a "Key" item from a list, then I grab the Object in the corresponding position and set the field's value to that.

But, when I reaches the mAge field I get the following message:

java.lang.IllegalArgumentException: Can not set int field Model.mAge to java.lang.String
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
at sun.reflect.UnsafeIntegerFieldAccessorImpl.set(UnsafeIntegerFieldAccessorImpl.java:98)

What I have possibly done wrong?





Aucun commentaire:

Enregistrer un commentaire