您需要禁止Java语言访问检查,以便使用setAccessible(true)反射地调用另一个类中的私有方法:
Method mtd= itr.getClass().getMethod("hasNext"); if(!mtd.isAccessible()) { mtd.setAccessible(true); }
此外,启用SecurityManager后,我们需要额外的权限才能调用setAccessible(true)。否则,我们得到:
C:ReflectionTest>java -Djava.security.manager CallFooException in thread "main" java.security.AccessControlException: access denied (java.lang.reflect.ReflectPermission suppressAccessChecks) at java.security.AccessControlContext.checkPermission(AccessControlContext.java:264) at java.security.AccessController.checkPermission(AccessController.java:427) at java.lang.SecurityManager.checkPermission(SecurityManager.java:532) at java.lang.reflect.AccessibleObject.setAccessible(AccessibleObject.java:107) at CallFoo.main(CallFoo.java:8)
我们只想向可信任的代码源(而不是对调用堆栈中的所有类)授予该excludeAccessChecks权限。因此,我们将修改CallFoo.java:
import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.security.AccessController;import java.security.PrivilegedActionException;import java.security.PrivilegedExceptionAction;public class CallFoo { public static void main(String args[]) throws Exception { doCallFoo(); } public static void doCallFoo() throws IllegalAccessException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, PrivilegedActionException { Class fooClass = Class.forName("Foo"); final Foo foo = (Foo) fooClass.newInstance(); final Method helloMethod = fooClass.getDeclaredMethod("hello"); AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws Exception { if(!helloMethod.isAccessible()) { helloMethod.setAccessible(true); } helloMethod.invoke(foo);return null; } }); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)