package com.xxxx;
import java.lang.reflect.Method;
/**
* 测试: 通过反射访问类私有成员
*
* @author Dw
*
*/
public class AccessPrivateMethodWithReflect
{
public static void main(String[] args)throws Exception
{
TestAccessPrivateMethod pm = new TestAccessPrivateMethod();
Class<?> classType = pm.getClass();
// 获取TestAccessPrivateMethod类的privateMethod方法原型
Method method = classType.getDeclaredMethod("privateMethod", String.class);
// 突破私有成员方法的private访问权限(只有getDeclaredMethod()方法返回的Method对象才能突破私有权限, getMethod()方法返回的Method对象则无此权限)
method.setAccessible(true);
// 调用私有方法(privateMethod(string));
method.invoke(pm, "Hello World"); // Hello World
}
}
class TestAccessPrivateMethod
{
// 私有方法
private void privateMethod(String str)
{
System.out.println(str);
}
}