Java Reflection: Access Private Constructors, Fields and Methods

By default private fields, methods and constructors are not accessible but using java reflection API setAccessible(true) on the instance of Field, Method and Constructor, we can access those.

In the below example, we will access private fields, methods and constructors of DummyClass in another class “ReflectionExample3“.

package com.java.reflection;

public class DummyClass {

    @Override
    public String toString() {
        return "DummyClass [privateVar=" + privateVar + ", id=" + id + "]";
    }

    private String privateVar = "123";

    private Integer id;

    private String privateMethod() {
        return "invoked private method";
    }

    public DummyClass(String privateVar) {
        this.privateVar = privateVar;
    }

    private DummyClass(Integer id) {
        this.id = id;
    }

    public DummyClass() {}

    private String privateMethodWithArgs(String arg) {
        return "invoked private method with arg:" + arg;
    }

    public String publicMethod() {
        return "invoked public method";
    }

}
package com.java.reflection;

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

public class ReflectionExample3 {

    public static void main(String[] args) {
        Class < DummyClass > clazz = DummyClass.class;
        try {
            // Invoke No Args Constructor
            Constructor < DummyClass > constructor = clazz.getConstructor();
            DummyClass dummyClassObj = constructor.newInstance();

            System.out.println("dummyClassObj:" + dummyClassObj);

            // Invoke Parameterized constructor
            Constructor < DummyClass > constructor1 = clazz.getConstructor(String.class);
            DummyClass dummyClassObj1 = constructor1.newInstance("testVar");

            System.out.println("dummyClassObj1:" + dummyClassObj1);

            // Invoke Private constructor
            Constructor < DummyClass > constructor2 = clazz.getDeclaredConstructor(Integer.class);
            constructor2.setAccessible(true);
            DummyClass dummyClassObj2 = constructor2.newInstance(5);

            System.out.println("dummyClassObj2:" + dummyClassObj2);

            // Access Private Field
            Field privateField = clazz.getDeclaredField("privateVar");
            privateField.setAccessible(true);
            String fieldValue = (String) privateField.get(dummyClassObj);
            System.out.println("private fieldValue = " + fieldValue);

            //Update Private Field Value
            privateField.set(dummyClassObj, "456");
            String updatedFieldValue = (String) privateField.get(dummyClassObj);
            System.out.println("updated private fieldValue = " + updatedFieldValue);

            // Invoke Private Method
            Method method = clazz.getDeclaredMethod("privateMethod");
            method.setAccessible(true);
            Object returnValue = method.invoke(dummyClassObj);
            System.out.println(returnValue);

            // Invoke Private Method with Arguments
            Method method1 = clazz.getDeclaredMethod("privateMethodWithArgs", String.class);
            method1.setAccessible(true);
            Object returnValue1 = method1.invoke(dummyClassObj, "test");
            System.out.println(returnValue1);

            // Invoke Public Method
            Method method2 = clazz.getDeclaredMethod("publicMethod");
            Object returnValue2 = method2.invoke(dummyClassObj1);
            System.out.println(returnValue2);
        } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException |
            IllegalArgumentException | InvocationTargetException | NoSuchFieldException e) {
            e.printStackTrace();
        }

    }



}
dummyClassObj:DummyClass [privateVar=123, id=null]
dummyClassObj1:DummyClass [privateVar=testVar, id=null]
dummyClassObj2:DummyClass [privateVar=123, id=5]
private fieldValue = 123
updated private fieldValue = 456
invoked private method
invoked private method with arg:test
invoked public method

Related Article

Java Reflection: List All Constructors,Methods and Fields

Leave a Reply

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