mardi 22 mars 2016

Whats the purpose of the primitive getter/setter in Field?

In the documentation for public Object get(Object obj) method in the Field class it is stated that

The value is automatically wrapped in an object if it has a primitive type.

and for public void set(Object obj, Object value) that

If the underlying field is of a primitive type, an unwrapping conversion is attempted to convert the new value to a value of a primitive type.

So am I right that the only purpose of the specific primitive getter and setter like getInt and setInt is to prevent a redundant type conversion?
Since this code works fine

public class Test{  
    int i = 1;
    public static void main(String[] args) throws Exception{
        Test inst = new Test();
        Class<?> clazz = inst.getClass();
        Field fi = clazz.getDeclaredField("i");
        int ii = (int) fi.get(inst);
        Integer iii = new Integer(ii * 2);
        fi.set(inst, iii);
    }
}

I am asking if someone knows a scenario that needs you to use these methods aside from performance reasons.





Aucun commentaire:

Enregistrer un commentaire