class Foo { private String message = "This is a Foo."; public void show() { System.out.println(message); } }
Class<Foo> fooClass = (Class<Foo>) foo.getClass(); Field messageField = fooClass.getDeclaredField("message"); messageField.setAccessible(true); // 绕过权限检测!
import java.lang.reflect.*; public class AccessPrivate { public static void main(String[] argv) throws Exception { // 定义一个测试对象 Foo foo = new Foo(); // 正常情况,测试函数 foo.show(); // 绕过Java权限检测 Class<Foo> fooClass = (Class<Foo>) foo.getClass(); Field messageField = fooClass.getDeclaredField("message"); messageField.setAccessible(true); // 绕过权限检测! System.out.println("Foo is hacked!"); // 修改message变量 messageField.set(foo, "This is a Bar."); // 再次调用测试函数 foo.show(); } } class Foo { private String message = "This is a Foo."; public void show() { System.out.println(message); } }
Java如何访问private变量?,布布扣,bubuko.com
原文地址:http://blog.csdn.net/caipeichao2/article/details/36220783