What is the purpose of a primitive getter / setter in a field?

The documentation for the public Object get(Object obj) method in the Field class states that

The value is automatically verified in the object if it has a primitive type.

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

If the base field is a primitive type, the sweep conversion attempts to convert the new value to a primitive type value.

Do I understand correctly that the sole purpose of a particular primitive getter and setter, such as getInt and setInt , is to prevent conversion of the redundant type?
Since this code is working 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 ask if anyone knows the script you need to use these methods aside from performance reasons.

+7
java reflection
source share
1 answer

This is for safety and efficiency type. Think of it differently - the get*() methods are the intended way to access primitive fields, and through get() just works, but boxing / unpacking is required.

In other words, the only reason for using get() in a primitive field is that you don't know its type ahead of time.

0
source share

All Articles