Monday, November 18, 2024
Google search engine
HomeLanguagesJavaHow to Access Private Field and Method Using Reflection in Java?

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

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 Java
import java.lang.reflect.Field;
  
// Student class declaration
class 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 IDE
class 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 Java
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
  
// Student class declaration
class 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

RELATED ARTICLES

Most Popular

Recent Comments