|
package com.test;
import java.lang.reflect.Field; import java.lang.reflect.Method; public class ReflectDemo { public static void main(String[] args) throws Exception { PrivateTest t = new PrivateTest(); Field field = Class.forName("com.test.PrivateTest").getDeclaredField( "str"); // 不让Java语言检查访问修饰符 field.setAccessible(true); field. set(t, "world"); t.getStr(); Method method2 = Class.forName("com.test.PrivateTest") .getDeclaredMethod("method", new Class[] {}); method2.setAccessible(true); method2. invoke(t, new Object[] {}); } } class PrivateTest { private String str = "hello"; public void getStr() { System.out .println("I'm str,I'm a private field,my old value is hello,now I am --->" + str); } private void method() { System.out.println("I'm in a private method!"); } } --------------结果--------------------- I'm str,I'm a private field,my old value is hello,now I am --->world I'm in a private method! |
本文通过一个Java示例展示了如何使用反射机制来访问并修改类的私有字段及调用私有方法。具体操作包括通过类名获取Class对象、设置字段可访问、修改私有字段值以及调用私有方法。

1546

被折叠的 条评论
为什么被折叠?



