Java面试题如何通过反射获取和设置对象私有字段的值
- java语言
- 关注:6.21K次
引导语:private关键字定义的都是私有字段,以下是本站小编分享给大家的Java面试题如何通过反射获取和设置对象私有字段的值?欢迎阅读学习!
如何通过反射获取和设置对象私有字段的值?
答:可以通过类对象的getDeclaredField()方法字段(Field)对象,然后再通过字段对象的setAccessible(true)将其设置为可以访问,接下来就可以通过get/set方法来获取/设置字段的.值了。下面的代码实现了一个反射的工具类,其中的两个静态方法分别用于获取和设置私有字段的值,字段可以是基本类型也可以是对象类型且支持多级对象操作,例如(dog, “”);可以获得dog对象的主人的汽车的引擎的ID号。
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 | import tructor; import d; import fier; import yList; import ; /**
* 反射工具类
* @author 骆昊
*
*/ public class ReflectionUtil {
private ReflectionUtil() {
throw new AssertionError();
}
/**
* 通过反射取对象指定字段(属性)的值
* @param target 目标对象
* @param fieldName 字段的名字
* @throws 如果取不到对象指定字段的值则抛出异常
* @return 字段的值
*/
public static Object getValue(Object target, String fieldName) {
Class<?> clazz = lass();
String[] fs = t( "." );
try {
for ( int i = 0 ; i < th - 1 ; i++) {
Field f = eclaredField(fs[i]);
ccessible( true );
target = (target);
clazz = lass();
}
Field f = eclaredField(fs[th - 1 ]);
ccessible( true );
return (target);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 通过反射给对象的指定字段赋值
* @param target 目标对象
* @param fieldName 字段的名称
* @param value 值
*/
public static void setValue(Object target, String fieldName, Object value) {
Class<?> clazz = lass();
String[] fs = t( "." );
try {
for ( int i = 0 ; i < th - 1 ; i++) {
Field f = eclaredField(fs[i]);
ccessible( true );
Object val = (target);
if (val == null ) {
Constructor<?> c = ype()eclaredConstructor();
ccessible( true );
val = nstance();
(target, val);
}
target = val;
clazz = lass();
}
Field f = eclaredField(fs[th - 1 ]);
ccessible( true );
(target, value);
}
catch (Exception e) {
throw new RuntimeException(e);
}
} } |
- 文章版权属于文章作者所有,转载请注明 https://xuezhezhai.com/jsj/java/53l6ml.html