Wednesday March 29, 2006
IllegalAccessException is not a SecurityException
java.lang.IllegalAccessException?
Is it caused by insufficient security permissions? Not
really. IllegalAccessException is not a subtype of java.lang.SecurityException.
Let's say you want to call a private method in anotehr class, which is
normally
not allowed by javac. But you know you can bypass javac with
reflection like this:1 import java.lang.reflect.Method;
2 public class CallFoo {
3 public static void main(String args[]) throws Exception {
4 Class fooClass = Class.forName("Foo");
5 Foo foo = (Foo) fooClass.newInstance();
6 Method helloMethod = fooClass.getDeclaredMethod("hello");
7 helloMethod.invoke(foo);
8 }
9 }
1 public class Foo {
2 private void hello() {
3 System.out.println("This is Foo.hello");
4 }
5 }
6 Method helloMethod = fooClass.getDeclaredMethod("hello");
7 if(!helloMethod.isAccessible()) {
8 helloMethod.setAccessible(true);
9 }
10 helloMethod.invoke(foo);
setAccessible(true).
Otherwise, we get:suppressAccessChecks permission
to trusted code source, definitely not to all classes in the call
stack. So we would modify CallFoo.java:1 import java.lang.reflect.InvocationTargetException;
2 import java.lang.reflect.Method;
3 import java.security.AccessController;
4 import java.security.PrivilegedActionException;
5 import java.security.PrivilegedExceptionAction;
6 public class CallFoo {
7 public static void main(String args[]) throws Exception {
8 doCallFoo();
9 }
10
11 public static void doCallFoo() throws IllegalAccessException, ClassNotFoundException, NoSuchMethodException,
12 InvocationTargetException, InstantiationException, PrivilegedActionException {
13 Class fooClass = Class.forName("Foo");
14 final Foo foo = (Foo) fooClass.newInstance();
15 final Method helloMethod = fooClass.getDeclaredMethod("hello");
16
17 AccessController.doPrivileged(new PrivilegedExceptionAction() {
18 public Object run() throws Exception {
19 if(!helloMethod.isAccessible()) {
20 helloMethod.setAccessible(true);
21 }
22 helloMethod.invoke(foo);
23 return null;
24 }
25 });
26 }
27 }
foo.policy:// Core classes get all permissions
grant codeBase "file:./-" {
permission java.lang.reflect.ReflectPermission
"suppressAccessChecks";
};
technorati tags: IllegalAccessException, setAccessible, suppressAccessChecks
Posted at 05:00PM Mar 29, 2006 by chengfang in Glassfish | Comments[2]
thanks alot this helped me out
Posted by craig e. on November 07, 2007 at 04:56 PM EST #
hi
Posted by 166.44.165.64 on November 18, 2009 at 07:59 AM EST #