Java get constructor

Java get constructor

To get a constructor of a class in Java, you can use the getConstructor() method of the Class class. This method takes one or more Class objects that specify the parameter types of the constructor, and returns a Constructor object that represents the constructor.

Here's an example of how to use the getConstructor() method to get a constructor of a class:

import java.lang.reflect.Constructor;

public class Main {
  public static void main(String[] args) throws Exception {
    Class cls = java.util.ArrayList.class;
    Constructor constructor = cls.getConstructor();
    System.out.println(constructor); // prints "public java.util.ArrayList()"
  }
}
So‮‬urce:www.lautturi.com

In this example, the getConstructor() method is called on the Class object for the java.util.ArrayList class to get the default (no-arg) constructor of the class. The Constructor object is then printed to the console.

You can also use the getConstructor(Class...) method to get a constructor of a class with specific parameter types. For example, to get the ArrayList constructor that takes an initial capacity as an argument, you can use the following code:

Class cls = java.util.ArrayList.class;
Constructor constructor = cls.getConstructor(int.class);
System.out.println(constructor); // prints "public java.util.ArrayList(int)"

Please note that the getConstructor() method throws a NoSuchMethodException if the specified constructor is not found, so you will need to handle this exception in your code.

Created Time:2017-11-03 22:21:03  Author:lautturi