There are situations where you want to access private member variables . An example of this is trying to access the socket fd (descriptor) from the Socket implementation in Java for doing some jni operations on it. The file descriptor is stored as a private member variable in the Socket class, and can be accessed using this example.
package org.best.example;
import java.lang.reflect.Field;
/**
* Class with the private variable
*/
class Hmmm
{
//private variable only accessible from this class
private int iWannaGoPublic=20;
}
/**
* Class with code to access the private variable in Hmmm
*/
public class ChangeAccessExample
{
public static void main(String[] args) throws Exception
{
Hmmm hmmmInstance=new Hmmm();
Class hmmClass = hmmmInstance.getClass();
Field f = hmmClass.getDeclaredField("iWannaGoPublic");
f.setAccessible(true); //Make the variable accessible
Object implVal = f.get(hmmmInstance);
int fd=((Integer) implVal).intValue();
System.out.println("Value of the private var is" + fd);
//Let me restore the access before someone finds out :-)
f.setAccessible(false);
}
}
No comments:
Post a Comment