日期:2014-05-20  浏览次数:20649 次

类的访问
如何在类的外部访问类内部的私有方法

------解决方案--------------------
使用反射机制,如下

import java.lang.reflect.Method;

class HelloWorld {

@SuppressWarnings("unused")
private void sayHello() {
System.out.println("私有方法也是可以调用的!");
}
}

public class PrivateReflect {

public static void main(String args[]) throws Throwable {
HelloWorld hello = new HelloWorld();
Method helloMethod = HelloWorld.class.getDeclaredMethod("sayHello");
helloMethod.setAccessible(true);
helloMethod.invoke(hello);
}
}

------解决方案--------------------
引用:
使用反射机制,
helloMethod.setAccessible(true);
……
-----------

高!

添个注解:
这个方案,有个使用前提,就是 在有 security manager 的环境里,需要 
ReflectPermission("suppressAccessChecks")。

一般在服务器侧,会用 security manager。