Java reflection (4)-get the construction method

We usually use the new operator to create new instances:

Person p = new Person();

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

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, Java's 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, the only difference is that it is a constructor, and the result of the call always returns an instance. Examples are as follows

public class Main {
    public static void main(String[] args) throws Exception {
        // 获取构造方法Integer(int):
        Constructor cons1 = Integer.class.getConstructor(int.class);
        // 调用构造方法:
        Integer n1 = (Integer) cons1.newInstance(123);
        System.out.println(n1);

        // 获取构造方法Integer(String)
        Constructor cons2 = Integer.class.getConstructor(String.class);
        Integer n2 = (Integer) cons2.newInstance("456");
        System.out.println(n2);
    }
}

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

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

Guess you like

Origin www.cnblogs.com/JohnTeslaaa/p/12716979.html