Access private fields and methods using reflection in java

In this post, we will see how to access private fields and methods using reflection in java.
[toc]
Can you access private fields and methods using reflection?
Yes, you can. It is very easy as well. You just need to call .setAccessible(true) on field or method object which you want to access.

Access private field

Class.getDeclaredField(String fieldName) or Class.getDeclaredFields() can be used to get private fields.

💡 Did you know?

Class.getField(String fieldName) and Class.getFields() return public fields only, so you won’t be able to get private fields with them

Let’s see this with the help of example:
Consider a class named Employee which consists of two private fields name and age.

 
package org.arpit.java2blog;

public class Employee {

    private String name;
    private int age;

    public Employee(String name, int age) {
        super();
        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 + "]";
    }
}

Create main class named PrivateFieldReflectionMain

package org.arpit.java2blog;

import java.lang.reflect.Field;

public class PrivateFieldReflectionMain {

    public static void main(String[] args) {
        try {
            Employee e=new Employee("John",30);

            Field privateField = Employee.class.getDeclaredField("name");

            privateField.setAccessible(true);

            String name=(String) privateField.get(e);
            System.out.println("Name of Employee:"+name);
        } catch (SecurityException | IllegalArgumentException | IllegalAccessException | NoSuchFieldException e) {
            e.printStackTrace();
        }
    }
}

When you run above class, you will get below output:
Output:

Name of Employee:John

As you can see, we are able to access private field name using reflection.

Access private method

If you want to invoke any method using reflection, you can go through invoke method using reflection.

Class.getDeclaredMethod(String methodName,Class<?>... parameterTypes) or Class.getDeclaredMethods() can be used to get private methods.

💡 Did you know?

Class.getMethod(String methodName,Class... parameterTypes) and Class.getMethods() return public methods only, so you won’t be able to get private methods with them

Let’s see this with the help of example:
We will access Employee‘s private method getAge() using reflection.

Create main class named

package org.arpit.java2blog;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class PrivateMethodReflectionMain {

    public static void main(String[] args) {
        try {
            Employee e=new Employee("Martin",33);

            Method privateMethod = Employee.class.getDeclaredMethod("getAge",null);

            privateMethod.setAccessible(true);

            int age=(int) privateMethod.invoke(e);
            System.out.println("Age of Employee: "+age);
        } catch (SecurityException | IllegalArgumentException | IllegalAccessException 
                  | NoSuchMethodException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}

When you run above class, you will get below output:
Output:

Age of Employee: 33

As you can see, we are able to access private method getAge() using reflection.
That’s about how to access private fields and methods using reflection in java

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.