If we want to access Private Field and method using Reflection we just need to call setAccessible(true) on the field or method object which you want to access. Class.getDeclaredField(String fieldName) or Class.getDeclaredFields() can be used to get private fields. Whereas Class.getDeclaredMethod(String methodName, Class<?>… parameterTypes) or Class.getDeclaredMethods() can be used to get private methods.
Below program may not work on online IDEs like, compile and run the below program on offline IDEs only.
1. Accessing private Field
Java
import java.lang.reflect.Field;
class Student {
private String name;
private int age;
public Student(String name, int age)
{
this .name = name;
this .age = age;
}
public String getName() { return name; }
public void setName(String name) { this .name = name; }
private int getAge() { return age; }
public void setAge( int age) { this .age = age; }
@Override public String toString()
{
return "Employee [name=" + name + ", age=" + age
+ "]" ;
}
}
class GFG {
public static void main(String[] args)
{
try {
Student e = new Student( "Kapil" , 23 );
Field privateField
= Student. class .getDeclaredField( "name" );
privateField.setAccessible( true );
String name = (String)privateField.get(e);
System.out.println( "Name of Student:" + name);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
|
Output:
Name of Student:Kapil
2. Accessing private Method
Java
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
class Student {
private String name;
private int age;
public Student(String name, int age)
{
this .name = name;
this .age = age;
}
public String getName() { return name; }
public void setName(String name) { this .name = name; }
private int getAge() { return age; }
public void setAge( int age) { this .age = age; }
@Override public String toString()
{
return "Employee [name=" + name + ", age=" + age
+ "]" ;
}
}
class GFG {
public static void main(String[] args)
{
try {
Student e = new Student( "Kapil" , 23 );
Method privateMethod
= Student. class .getDeclaredMethod( "getAge" );
privateMethod.setAccessible( true );
int age = ( int )privateMethod.invoke(e);
System.out.println( "Age of Student: " + age);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
|
Output:
Age of Student: 23