views:

65

answers:

2

I have the following class

public class MyClass {
   private int myAttr;

   public void setAttr(int a) { 
      myAttr = a; 
      Thread.dumpStack();
   }
}

That way I can detect any attempt to modify myAttr. Well, almost any. It does not work when someone modifies myAttr using Field.set() method. How can I trap Java reflection usage?

+5  A: 

You can't. You're at the mercy of the SecurityManager, if one is around, to prevent anyone else from doing nasty things to you.

Related question

polygenelubricants
+1  A: 

First you need to ask yourself what you are really worried about here. Sure - if someone really wanted to, they could subvert your stack tracer. But why do you really care? And if you do really care, why are you prepared to run their code at all?

If you really need to do this, you need to create a security sandbox in which to run code that might subvert your stack tracer. Specifically, you need to create a security manager for which

    securityManager.checkPermission(ReflectPermission("suppressAccessChecks"))

will throw a SecurityException for untrusted code. Then you create a new classloader using the security manager.

Unfortunately, there doesn't appear to be a way to restrict setAccessible(...) for particular target fields, methods or classes.

Stephen C
Thanks for your answer. My class is part of a big project and I want to know who modifies my attribute. It might be modified by a third-party framework (toplink) as well. I will try to create a security sandbox as you advised.
Oleg Pavliv