- The Problem of Encapsulation
- Accessing Packages and Protected Class Members
- Accessing Private Class Members
- Quick Quiz
- In Brief
Accessing Private Class Members
Private members are accessible only to the class that declares them. That is one of the ground rules of the Java language that ensures encapsulation. But is it really so? Is it really enforced all the time? If you said, "Well, this guy is writing about it, so there has to be a loophole of some sort," you'd be right. The Java compiler enforces the privacy of private members at compile time. Thus, there can be no static references by other classes to private methods and variables of a class. However, Java has a powerful mechanism of reflection that enables querying instance and class metadata and accessing fields and methods at runtime. Because reflection is dynamic, compile time checks are not applicable. Instead, Java runtime relies on a security managerif one existsto verify that the calling code has enough privileges for a particular type of access. The security manager provides enough protection because all the functions of the reflection API delegate to it before executing their logic. What undermines this protection is the fact that the security manager is often not set. By default, the security manager is not set, and unless the code explicitly installs a default or a custom security manager, the runtime access control checks are not in effect. Even if a security manager is set, it is typically configured through a policy file, which can be extended to allow access to the reflection API.
If you looked at the BorderLayout class carefully, you might have noticed that it already has a method that returns a child component based on the position key. Not surprisingly, it is called getChild and has the following signature:
private Component getChild(String key, boolean ltr)
This sounds like good news because you don't really have to write your own implementation. The problem is that the method is declared as private and there is no public method you can use to call it. To leverage the existing JDK code, you must call BorderLayout.getChild() using the reflection API. We will use the same test structure as in the previous section. This time, though, instead of using AwtHelper, the test class delegates to its own helper function (getChild()):
public class PrivateAccessTest { public static void main(String[] args) throws Exception { Container container = createTestContainer(); if (container.getLayout() instanceof BorderLayout) { BorderLayout layout = (BorderLayout)container.getLayout(); Component center = getChild(layout, BorderLayout.CENTER); System.out.println("Center component = " + center); } ... } public static Component getChild(BorderLayout layout, String key) throws Exception { Class[] paramTypes = new Class[]{String.class, boolean.class}; Method method = layout.getClass().getDeclaredMethod("getChild", paramTypes); // Private methods are not accessible by default method.setAccessible(true); Object[] params = new Object[] {key, new Boolean(true)}; Object result = method.invoke(layout, params); return (Component)result; } ... }
The getChild() implementation is the core of the technique. It obtains the method object through reflection and then calls setAccessible(true). A value of true is set to suppress the access control checking and allow method invocation. The rest of the method is plain reflection API usage. Running covertjava.visibility.PrivateAccessTest produces the same output you saw in the previous section:
C:\Projects\CovertJava\distrib\bin>private_access_test.bat Testing private access Center component = javax.swing.JSplitPane[,0,0,0x0,...]
This was alarmingly easy. We might have to do a little more work if a security manager is set using System.setSecurityManager or via a command line, which is the case for most application servers and middleware products. If we run our test passing -Djava.security.manager to the java command line, we get the following exception:
java.security.AccessControlException: access denied (java.lang.RuntimePermission accessDeclaredMembers)
For our code to work with a security manager installed, we have to grant the permissions to access declared members through reflection and to suppress access checks. We do so by adding a Java policy file that grants these two permissions to our code base:
grant { permission java.lang.RuntimePermission "accessDeclaredMembers"; permission java.lang.reflect.ReflectPermission "suppressAccessChecks"; };
Finally, we create a new test script (private_access_test.bat) in the distrib\bin directory that adds a command-line parameter (java.security.policy) to install our policy file:
set CLASSPATH=..\lib\chat.jar set JAVA_ARGS=%JAVA_ARGS% -Djava.security.manager set JAVA_ARGS=%JAVA_ARGS% -Djava.security.policy=../conf/java.policy java %JAVA_ARGS% covertjava.visibility.PrivateAccessTest
If a policy file is already installed, our grant clause needs to be inserted into it. Java security files allow inclusion of additional policy files using the policy.url.n attribute. See Chapter 7, "Manipulating Java Security," for a detailed discussion of Java security and policy files.
The technique that relies on the reflection API can be used to access package and protected members as well. This makes inserting helper classes into third-party packages unnecessary. The drawback of the reflection API is that it is notoriously slow because it has to deal with runtime information and might have to go through a number of security checks. When speed is an issue, it is preferable to rely on the helper classes for package and protected members. Yet another alternative is serializing an instance into a byte array stream and then parsing the stream to obtain the values of the member variables. Obviously, this is a tedious process that does not work for transient fields.