Java – what is the purpose of the original getter / setter in the field?
•
Java
This is explained in the documentation of the public object get (object obj) method of the field class
And for public void set (object obj, object value)
So I'm right. The only purpose of specific original getters and setters such as getInt and setint is to prevent redundant type conversion? Because this code works correctly
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 scenarios where you need to use these methods, except for performance reasons
Solution
This is for type safety and efficiency Also consider that the – get * () method is the expected way to access the original field, and doing so through get () just works, but requires boxing / unboxing
In other words, the only reason to use get () on the original field is if you don't know its type in advance
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码