Java Language Reflection API Call constructor

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Getting the Constructor Object

You can obtain Constructor class from the Class object like this:

Class myClass = ... // get a class object
Constructor[] constructors = myClass.getConstructors();

Where the constructors variable will have one Constructor instance for each public constructor declared in the class.

If you know the precise parameter types of the constructor you want to access, you can filter the specific constructor. The next example returns the public constructor of the given class which takes a Integer as parameter:

Class myClass = ... // get a class object
Constructor constructor = myClass.getConstructor(new Class[]{Integer.class});

If no constructor matches the given constructor arguments a NoSuchMethodException is thrown.

New Instance using Constructor Object

Class myClass = MyObj.class // get a class object
Constructor constructor = myClass.getConstructor(Integer.class);
MyObj myObj = (MyObj) constructor.newInstance(Integer.valueOf(123));


Got any Java Language Question?