My question is how can we change the security manager to not allow this. Also is it possible to do this out of java code, in a policy file. Preferably the existing policy file that comes with the JRE.
Thanks in advance, -Chinmay
The strength of the Wolf is the pack & the strength of the pack is the wolf....Rudyard Kipling
Joined: Jul 22, 2006
I don't know if it's possible or not (I'd say it probably isn't), but why would you want to do that anyway? Access modifiers are there to help developers; they're not a security mechanism. You label methods and fields as private to keep other developers (and yourself!) from directly using them. See the "information hiding" principle of OO design.
If another developer wants to go crazy with reflection in order to defeat your API, that's their problem, not yours. Chances are their code will break when you start refactoring the internals anyway.
I wouldn't bother if even Sun haven't secured the core Java API:
abcd, bcd abcf, bcf abcf, abc
As you can see this breaks all assumptions any Java developer has ever made about Strings - that they are immutable. Even worse, because Strings can share the internal char arrays, changing one can many others as well.
So yeah, if Sun couldn't secure something as important as this, then I don't think you can secure your methods.
To block such reflective access, you need a SecurutyManager. By default, Java applications have no SecurityManager. This means if you start java from the command line, you own that process, and you have ultimate authority to do whatever you want in that process. It's your own fault if you misuse reflection. However, if you plan to run code from untrusted third parties, then you can install a SecurityManager:
This new SecurityManager will get its permissions from the system and user policy files (if present). See here for more info. By default, the standard system policy file on your system does not allow reflective access to private members, so you should be covered. You may then want to further edit the policy file if it ends up prohibiting some thigns you want to do - that's your call.