IllegalAccessException using reflection on private field
jxhill May 21, 2007 5:20 PMI have an app that relies heavily on reflection. I want to use AOP with it, but I get an error when accessing a private variable through java.lang.reflect.Field. It appears that aspects disables the call to Field.setAccessible(); The following sample code works fine until I apply aspects.
// TestObject.java package test; public class TestObject { @SuppressWarnings("unused") private String testField = "Initial Value"; }
// TestAspect.java package test; import org.jboss.aop.joinpoint.FieldReadInvocation; import org.jboss.aop.joinpoint.FieldWriteInvocation; public class TestAspect { public Object accessField(FieldReadInvocation invocation) throws Throwable { return invocation.invokeNext(); } public Object accessField(FieldWriteInvocation invocation) throws Throwable { return invocation.invokeNext(); } }
// Main.java package test; import java.lang.reflect.Field; public class Main { public static void main(String[] args) { TestObject test = new TestObject(); fieldReadTest(test); out(""); fieldWriteTest(test, "Some new value"); out(""); fieldReadTest(test); } public static void fieldWriteTest(TestObject test, Object newValue) { infoOut("Begin Field Write Test"); try { Field f = TestObject.class.getDeclaredField("testField"); f.setAccessible(true); f.set(test, newValue); infoOut("End Field Write Test - Success") ; } catch(Exception e) { out(e); infoOut("End Field Write Test - FAILED"); } } public static void fieldReadTest(TestObject test) { infoOut("Begin Field Read Test"); try { Field f = TestObject.class.getDeclaredField("testField"); f.setAccessible(true); System.out.println(String.valueOf(f.get(test))); infoOut("End Field Read Test - Success") ; } catch(Exception e) { out(e); infoOut("End Field Read Test - FAILED"); } } private static void infoOut(String s) { System.out.println("[" + s + "]"); } private static void out(Object o) { System.out.println(o.toString()); } }
jboss-aop.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <aop> <aspect name="ReflectionAspect" class="org.jboss.aop.reflection.ReflectionAspect" scope="PER_VM"/> <bind pointcut="call(* java.lang.reflect.Field->get*(..))"> <advice name="interceptFieldGet" aspect="ReflectionAspect"/> </bind> <bind pointcut="call(* java.lang.reflect.Field->set*(..))"> <advice name="interceptFieldSet" aspect="ReflectionAspect"/> </bind> <aspect class="test.TestAspect" scope="PER_VM"/> <bind pointcut="field(* test.TestObject->*)"> <advice name="accessField" aspect="test.TestAspect"/> </bind> </aop>
Am I doing something wrong, or is this a bug?