Skip to content
On this page

Call Constructor

We usually use the new operator to create new instances:

java
Person p = new Person();

If you create a new instance through reflection, you can call the newInstance() method provided by Class:

java
Person p = Person.class.newInstance();

The limitation of calling Class.newInstance() is that it can only call the public parameterless constructor of the class. If the constructor has parameters or is not public, it cannot be called directly through Class.newInstance() .

In order to call any constructor method, Java's reflection API provides a Constructor object, which contains all the information of a constructor method and can create an instance. The Constructor object is very similar to the Method, the only difference is that it is a constructor method, and the call result always returns an instance:

java
import java.lang.reflect.Constructor;

public class Main {
    public static void main(String[] args) throws Exception {
        // Get the constructor Integer(int):
        Constructor cons1 = Integer.class.getConstructor(int.class);
        // Call constructor:
        Integer n1 = (Integer) cons1.newInstance(123);
        System.out.println(n1);

        // Get the constructor Integer(String)
        Constructor cons2 = Integer.class.getConstructor(String.class);
        Integer n2 = (Integer) cons2.newInstance("456");
        System.out.println(n2);
    }
}

The method of obtaining Constructor through Class instance is as follows:

  • getConstructor(Class...) : Get a public Constructor ;
  • getDeclaredConstructor(Class...) : Get a Constructor ;
  • getConstructors() : Get all public Constructor ;
  • getDeclaredConstructors() : Get all Constructor .

Note Constructor is always the constructor defined by the current class and has nothing to do with the parent class, so there is no polymorphism problem.

When calling a non-public Constructor , you must first set setAccessible(true) to allow access. setAccessible(true) may fail.

Summary

The Constructor object encapsulates all information about the construction method;

Constructor instances can be obtained through the methods of Class instances: getConstructor() , getConstructors() , getDeclaredConstructor() , getDeclaredConstructors() ;

An instance object can be created through a Constructor instance: newInstance(Object... parameters) ; Access non-public constructors by setting setAccessible(true) .

Call Constructor has loaded