The following program is accessing and modifying a private field named privateKey declared within the class SimpleKeyPair. Let’s have a look at it.
package mod;
import java.lang.reflect.Field;
import java.util.logging.Level;
import java.util.logging.Logger;
final class SimpleKeyPair
{
private String privateKey = "Welcome SimpleKeyPair ";
}
final public class Main
{
public static void main(String[] args)
{
SimpleKeyPair keyPair = new SimpleKeyPair();
Class c = keyPair.getClass();
try
{
Field field = c.getDeclaredField("privateKey"); // gets the reflected object
field.setAccessible(true);
System.out.println("Value of privateKey: " + field.get(keyPair)); // displays “Welcome SimpleKeyPair"
field.set(keyPair, "Welcome PrivateMemberAccessTest"); // modifys the private member varaible
System.out.println("Value of privateKey: " + field.get(keyPair));
}
catch (IllegalArgumentException ex)
{
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IllegalAccessException ex)
{
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
catch (NoSuchFieldException ex)
{
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
catch (SecurityException ex)
{
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
In the code above, the private field privateKey declared within the class SimpleKeyPair is being accessed and displayed on the console through the following statements.
Field field = c.getDeclaredField("privateKey");
field.setAccessible(true);
System.out.println("Value of privateKey: " + field.get(keyPair));
and that field is being modified and the new value of that field is being displayed through the following statements.
field.set(keyPair, "Welcome PrivateMemberAccessTest");
System.out.println("Value of privateKey: " + field.get(keyPair));
The actual output of the program would be as under.
Value of privateKey: Welcome SimpleKeyPair
Value of privateKey: Welcome PrivateMemberAccessTest
Means that the use of reflection in Java allows a direct access to private resources. If it is so then, declaring a member as private itself in Java is not safe though one of the aims of declaring class members as private is to hide them from outside the world. What is the actual use of reflection in Java?
You are correct that reflection can allow access to private (and package and protected) scoped members of a class. However, if you read the JavaDocs, you will find that all of the methods for fetching and invoking these accessors perform a SecurityManager check before performing the requested operation. So, in an environment with a SecurityManger, the operations will fail with SecurityExceptions being thrown.