November 11, 2020

Use java reflection api to access private constructor of a class and create an instance

This code will work in Java 9 and above.

You can watch my Youtube video, where I am working on this code.

In java, we can use reflection apis to access all the properties of a java class.

In this blog, I will show you how you can make a private constructor public and use it to create an instance of that class.

I will create a a class Person, with a private constructor.

public class Person{
    private final String firstName;
    private final String lastName;

    private Person(final String firstName, final String lastName){
        this.firstName = firstName;
    this.lastName = lastName;
    }

    public String getFirstName(){ return this.firstName; }
    public String getLastName() { return this.lastName; }

    @Override
    public String toString(){
        return "{ FirstPerson : " + this.firstName+ ", LastPerson : " + this.lastName + "}";
    }
}

To create an instance, first you need to get a reference to that constructor.

Class<Person> personClass = Person.class;
Constructor<?>[] constructors = personClass.getDeclaredConstructors();
Constructor<?> privateConstructor = constructors[0];

We get a reference to the class object, then we get a reference to array of constructors. As we know, we have only one constructor, so we can get a reference to that by accessing index-zero of array of constructor.

Once we have access to the constructor object, we make that constructor accessible.

privateConstructor.setAccessible(true);

Then we call newInstance method on it, with proper arguments.

final Person person = (Person) privateConstructor.<Person>newInstance("Anurag", "Anand");
System.out.println(person);

Full Source Code :-

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

public class ReflectTest{
    
    public static void main(final String ... args) 
                                                throws 
                            InstantiationException,
                            IllegalAccessException,
                            InvocationTargetException
                            {
        Class<Person> personClass = Person.class;
    Constructor<?>[] constructors = personClass.getDeclaredConstructors();
    Constructor<?> privateConstructor = constructors[0];
    privateConstructor.setAccessible(true);

    final Person person = (Person) privateConstructor.<Person>newInstance("Anurag", "Anand");
    System.out.println(person);
    }
}