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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With