ArcticLord ArcticLord - 6 months ago 9
Java Question

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.

Answer

It's for both type-safety and efficiency. Think about it the other way - the get*() methos are the intended way to access primitive fields, and doing so via get() just happens to work as well but requires boxing/unboxing.

In other words the only reason to use get() on a primitive field is if you don't know its type ahead of time.