« A Google IM Client? | Main | Just Added - Del.icio.us Bookmarks on Sidebar »
August 29, 2005
Java - 'private' does not really mean Private...
In the following example, I am going to show how to access private fields and methods from another Java class using Reflection. Typically, private access from another class is not allowed in Java. However, the AccessibleObject class, which is the parent class of Field and Method (among others) contains a method called setAccessible(boolean flag), which allows a programmer to override the permissions governing access to private fields and methods.
Take a look at these two example classes:
Private.java
PrivateTest.java
Private.java contains a private int field, String field and void method, none of which should be accessible outside the class. However, PrivateTest.java uses reflection to call setAccessible(true) and gains access to all of these members. It then prints the values of the private fields and invokes the private method.
Is there any way around this? Kind of. By invoking the JVM with "-Djava.security.manager" (no quotes), the JVM will be using the Java Security Manager, which will throw an error whenever setAccessible(true) is called to access a private method when it shouldn't. The specific error will be:
java.security.AccessControlException: access denied (java.lang.reflect.ReflectPermission suppressAccessChecks)
In addition, the JVM argument "-Djava.security.policy" (again, no quotes) allows you to use a custom security policy file that lets you be very specific as to what is allowed and what is not. More information on security policies is available here. However, there is no way to guarantee that a user will be using the Security Manager with your specific policies being enforced.
So what does this mean? Basically, if someone really wants to access a private field or method in any Java class, they can do so. As you code anything private, you should at least be aware of this, especially if what you are coding is proprietary or confidential.
The best analogy I can give is about locks on a house. If your house has locks, it may deter some people from breaking in and robbing you. However, if someone really wants to gain access, a lock is not going to stop them. The same is true for private methods in Java.
Posted by Chuck at August 29, 2005 11:20 AM
Trackback Pings
TrackBack URL for this entry:
http://www.chuckcaplan.com/blog/mt-tb.cgi/27
Comments
Oh, ok. That's what I figured.
Posted by: Chris at August 30, 2005 04:43 PM