使用JAVA反射示例,反射修改字段属性值和方法参数
public class ReflectionTest {
private String test = "test";
private static String static_test= "static_test";
private String getName(String args){
return args + "name";
}
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException, ClassNotFoundException, InstantiationException, NoSuchMethodException, InvocationTargetException {
//修改前
System.out.println("before:" + new ReflectionTest().test);
System.out.println("before:" + static_test);
System.out.println("before:" + new ReflectionTest().getName("参数"));
//修改后
//查找类名
Class<?> clazz = Class.forName("ReflectionTest");
//实例化对象
Object obj = clazz.newInstance();
//获取字段
Field field = clazz.getDeclaredField("test");
//私有字段需要设置权限为true
field.setAccessible(true);
//修改字段值
field.set(obj,"changeTest");
System.out.println("after:" + field.get(obj));
field = clazz.getDeclaredField("static_test");
field.setAccessible(true);
//注意,这里修改的是静态字段,不需要实例化对象
field.set(clazz,"changeStaticTest");
System.out.println("after:" + field.get(clazz));
Method method = clazz.getDeclaredMethod("getName", String.class);
//一样,私有方法需要设置权限
method.setAccessible(true);
//反射修改方法参数
//需要调用实例化对象
Object result = method.invoke(obj,"changeArgs");
System.out.println("after:" + result.toString());
}
}
运行结果:
before:test
before:static_test
before:参数name
after:changeTest
after:changeStaticTest
after:changeArgsname
评论(0)