By now, we have learned how to access fields and calling methods of a class through Java reflection. This article will simply show how to call constructors by Java reflection.

Calling constructor

We usually use newoperators to create new instances:

Person p = new Person();

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

Person p = Person.class.newInstance();

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

In order to call arbitrary constructors, Java reflection API provides a Constructor object, which contains all the information of a constructor, and can create an instance. Constructor object is very similar to Method except that it is a constructor method, and the result of the call always returns an instance.

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

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

The method for obtaining a Constructor through a Class instance is as follows:

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

Note that Constructoris always the constructor of the current class and independent of the parent class, so there is no polymorphism.

When calling non public Constructor, you must first call setAccessible(true)to allow access by setting. 

summary

Constructor object encapsulates all the information of the constructor.

By Classinstance’s method may obtain the instance of Constructor.

Constructor instance can create an instance of an object instance.