This example shows how to get the constructors in a class and invoke it. Note that java.lang.reflect.Constructor defines a method newInstance() which is used for creating instance for an object. Before that you have to get the list of constructors in a class. We have two methods defined in the Class class. If we use getConstructors() method, it returns only the public constructors in that class. If we use getDeclaredConstructor() method, it returns all the constructors in that class.
Lets look at the example code.
package javabeat.net.reflection; import java.lang.reflect.Constructor; /** * Get Constructors using Reflection * * @author krishna * */ public class JavaBeatReflectionExample { private JavaBeatReflectionExample() { System.out.println("Default Constructor Called"); } public JavaBeatReflectionExample(int i) { System.out.println("One Parameter Constructor Called"); } public static void main(String[] args) throws Exception { JavaBeatReflectionExample reflectionExample = new JavaBeatReflectionExample(); // Get all the constructors Constructor cons[] = reflectionExample.getClass().getDeclaredConstructors(); cons[0].newInstance(); cons[1].newInstance(9); } }
Output
Default Constructor Called Default Constructor Called One Parameter Constructor Called