当前位置: 代码迷 >> Java相关 >> 种的访问
  详细解决方案

种的访问

热度:330   发布时间:2016-04-22 21:56:49.0
类的访问
如何在类的外部访问类内部的私有方法

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

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。

  相关解决方案