Java Reflection API provides a feature to access private members of a Java Class.
java.lang.reflect package provides the AccessibleObject class that is parent class of Constructor, Method, and Field class. Using the AccessibleObject class, we can change the access control flags of a Reflection Object
Lets understand how to achieve this with below example.
Class Having Private Members[MyClass.java]
package in.bibek;
public class MyClass
{
private String name = "Bibek";
private String org = "Aon Hewitt";
public String address = "Delhi";
private void privateMethod(String aName)
{
name = aName;
System.out.println("Inside Private Method of Class -Name is :"+name);
}
}
Class to Access the private members of the above class using Reflection[MainClass.java]
package in.bibek;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class MainClass
{
public static void main(String[] args) throws SecurityException,
NoSuchFieldException, IllegalArgumentException, IllegalAccessException,
NoSuchMethodException, InvocationTargetException
{
MyClass myObj = new MyClass();
//System.out.println(myObj.name); cannt access
System.out.println("Address as Public Field "+myObj.address);
Class myObjClass = myObj.getClass();
Field nameFld = myObjClass.getDeclaredField("name");
Field orgFld = myObjClass.getDeclaredField("org");
nameFld.setAccessible(true);
orgFld.setAccessible(true);
System.out.println("value of private name field is : " + nameFld.get(myObj));
System.out.println("value of private Organization field is : " + orgFld.get(myObj));
//Accessing Private Methods
Method method = myObjClass.getDeclaredMethod("privateMethod",String.class);
method.setAccessible(true);
method.invoke(myObj,"Mishra");
}
}
Leave a Reply