Accessing and modifying private class members through the use of reflection in Java
<p>The following program is accessing and modifying a private field named <code>privateKey</code> declared within the class <code>SimpleKeyPair</code>. Let's have a look at it.</p>

<pre><code>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);
        }
    }
}
</code></pre>

<hr>

<p>In the code above, the private field <code>privateKey</code> declared within the class <code>SimpleKeyPair</code> is being accessed and displayed on the console through the following statements.</p>

<pre><code>Field field = c.getDeclaredField("privateKey"); 
field.setAccessible(true);
System.out.println("Value of privateKey: " + field.get(keyPair));
</code></pre>

<hr>

<p>and that field is being modified and the new value of that field is being displayed through the following statements.</p>

<pre><code>field.set(keyPair, "Welcome PrivateMemberAccessTest"); 
System.out.println("Value of privateKey: " + field.get(keyPair));
</code></pre>

<hr>

<p>The actual output of the program would be as under.</p>

<pre><code>Value of privateKey: Welcome SimpleKeyPair 
Value of privateKey: Welcome PrivateMemberAccessTest
</code></pre>

<hr>

<p>Means that the use of <strong>reflection</strong> in Java allows a direct access to private resources. If it is so then, declaring a member as <strong>private</strong> 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?</p>
