在
Field类的公共Object get(Object obj)方法的文档中说明了这一点
The value is automatically wrapped in an object if it has a primitive
type.
并且对于public void set(Object obj,Object value)
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.
所以我是对的,特定的原始getter和setter如getInt和setInt的唯一目的是防止冗余类型转换?
由于此代码工作正常
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);
}
}
我问的是,除了性能原因,是否有人知道需要您使用这些方法的场景.