Java通过反射设置私有变量
- public class PrivateTest {
- private String name = "hello";
- public String getName() {
- return name;
- }
- }
- import java.lang.reflect.Field;
- public class ReflectionTest {
- public static void main(String[] args) throws Exception {
- PrivateTest pt = new PrivateTest();
- Class<PrivateTest> clazz = PrivateTest.class;
- Field field = clazz.getDeclaredField("name");
- field.setAccessible(true);
- field.set(pt, "world");
- field.setAccessible(false);
- System.out.println(pt.getName());
- }
- }