java 反射私有变量赋值_通过反射,操作私有成员变量(取/赋值),调用私有方法...
Java的反射工具很強大,有句著名的話:No reflection ,no frameworks.
工作中直到涉及到UT,才體會到它的重要性,現(xiàn)歸納整理一個小例子:
反射工具類:import?java.lang.reflect.Field;
import?java.lang.reflect.InvocationTargetException;
import?java.lang.reflect.Method;
public?class?ReflectionUtil?{
/***
*?獲取私有成員變量的值
*
*/
public?static?Object?getValue(Object?instance,?String?fieldName)
throws?IllegalAccessException,?NoSuchFieldException?{
Field?field?=?instance.getClass().getDeclaredField(fieldName);
field.setAccessible(true);?//?參數(shù)值為true,禁止訪問控制檢查
return?field.get(instance);
}
/***
*?設(shè)置私有成員變量的值
*
*/
public?static?void?setValue(Object?instance,?String?fileName,?Object?value)
throws?NoSuchFieldException,?SecurityException,?IllegalArgumentException,?IllegalAccessException?{
Field?field?=?instance.getClass().getDeclaredField(fileName);
field.setAccessible(true);
field.set(instance,?value);
}
/***
*?訪問私有方法
*
*/
public?static?Object?callMethod(Object?instance,?String?methodName,?Class[]?classes,?Object[]?objects)
throws?NoSuchMethodException,?SecurityException,?IllegalAccessException,?IllegalArgumentException,
InvocationTargetException?{
Method?method?=?instance.getClass().getDeclaredMethod(methodName,?classes);
method.setAccessible(true);
return?method.invoke(instance,?objects);
}
}package?com.test;
public?class?Person?{
private?String?name;
private?int?age;
public?Person(String?name,?int?age)?{
this.name?=?name;
this.age?=?age;
}
private?String?getInfo(String?str,?int?num)?{
return?str?+?num?+?"?apples";
}
}import?com.test.Person;
public?class?ReflectTest?{
public?static?void?main(String[]?args)?throws?Exception?{
Person?person?=?new?Person("jack",?25);
//?test?get?private?value
System.out.println("jack's?name:"?+?ReflectionUtil.getValue(person,?"name"));
System.out.println("jack's?age:"?+?ReflectionUtil.getValue(person,?"age"));
//?test?set?private?value
ReflectionUtil.setValue(person,?"name",?"jason");
ReflectionUtil.setValue(person,?"age",?10);
System.out.println("jack's?name:"?+?ReflectionUtil.getValue(person,?"name"));
System.out.println("jack's?age:"?+?ReflectionUtil.getValue(person,?"age"));
//?test?call?private?method
String?result?=?(String)?ReflectionUtil.callMethod(person,?"getInfo",?new?Class[]?{?String.class,?int.class?},
new?Object[]?{?"I?hava?",?4?});
System.out.println("result:?"?+?result);
}
}結(jié)果:
jack's?name:jack
jack's?age:25
jack's?name:jason
jack's?age:10
result:?I?hava?4?apples
總結(jié)
以上是生活随笔為你收集整理的java 反射私有变量赋值_通过反射,操作私有成员变量(取/赋值),调用私有方法...的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: java web json_java w
- 下一篇: java程序math包没有_java.m
