- 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());
- }
- }
参考:http://www.iteye.com/problems/38606