Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect when an attribute is modified by calling reflection methods

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?

like image 631
Oleg Pavliv Avatar asked May 12 '10 11:05

Oleg Pavliv


2 Answers

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

  • How to limit setAccessible to only “legitimate” uses?
like image 146
polygenelubricants Avatar answered Oct 13 '22 02:10

polygenelubricants


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.

like image 29
Stephen C Avatar answered Oct 13 '22 03:10

Stephen C