Accessing private members outside a Java class…
In a discussion with my colleague, who was bored of writing getter and setter methods for member variables in a Java class, was wondering if there is way to access a private variable or a method of a class outside its scope in a different class. In C++ world, this is quite very much possible using friend classes or probably accessing the address of the object to the class…
In the Java world as well, this is a long existing feature since the introduction of the reflection APIs. A sample code below illustrates how it can be done simply:
A TestObject that has a private member without any public getter and setter methods.
package one;
public class TestObject {
private String testStr = "Hello World!";
}
An AccessTest class that reads the value of testStr private member using an object of TestObject class.
package two;
import java.lang.reflect.Field;
import one.TestObject;
public class AccessTest {
public static void main(String[] args) {
try {
Class tObjClass = Class.forName("one.TestObject");
Field tField = tObjClass.getDeclaredField("testStr");
tField.setAccessible(true);
System.out.println("TestStr Value: "+tField.get(new TestObject()));
} catch (Exception e) {
e.printStackTrace();
}
}
}
Using the java.lang.reflect APIs any private member or method of a class can be accessed from anywhere. One way to prevent this access is to run the program using a security manager as below:
java –Djava.security.manager AccessTest
would give the below exception:
access denied (java.lang.reflect.ReflectPermission suppressAccessChecks)
This feature is quite useful in unit testing when there is a need to test the private methods using a test suite.