How to Access Private Field and Method Using Reflection in Java?

05 Feb, 2021
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
// Access Private Field Using Reflection in Javaimport java.lang.reflect.Field;  // Student class declarationclass Student {      // private fields    private String name;    private int age;      // Constructor    public Student(String name, int age)    {        this.name = name;        this.age = age;    }      // Getters and setters    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 toString method to get required    // output at terminal    @Override public String toString()    {        return "Employee [name=" + name + ", age=" + age            + "]";    }}  // Program will throw an exception on online IDE// Compile and run the program on offline IDEclass GFG {      public static void main(String[] args)    {        try {              // Student object created            Student e = new Student("Kapil", 23);              // Create Field object            Field privateField                = Student.class.getDeclaredField("name");              // Set the accessibility as true            privateField.setAccessible(true);              // Store the value of private field in variable            String name = (String)privateField.get(e);              // Print the value            System.out.println("Name of Student:" + name);        }        catch (Exception e) {            e.printStackTrace();        }    }}
Output:
Name of Student:Kapil
2. Accessing private Method
Java
// Access Private Method Using Reflection in Javaimport java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;  // Student class declarationclass Student {      // Private fields    private String name;    private int age;      // Constructor    public Student(String name, int age)    {        this.name = name;        this.age = age;    }      // Getters and Setters    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 to string method to get    // Required output when called    @Override public String toString()    {        return "Employee [name=" + name + ", age=" + age            + "]";    }}  class GFG {      public static void main(String[] args)    {        try {            // Student class object            Student e = new Student("Kapil", 23);              // Create Method object            Method privateMethod                = Student.class.getDeclaredMethod("getAge");              // Set the accessibility as true            privateMethod.setAccessible(true);              // Store the returned value of            // private methods in variable            int age = (int)privateMethod.invoke(e);            System.out.println("Age of Student: " + age);        }        catch (Exception e) {            e.printStackTrace();        }    }}
Output:
Age of Student: 23
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array