Get constructor of a class object using Reflection

Reflection In Java : 
Reflection is a feature in the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program. For example, it's possible for a Java class to obtain the names of all its members and display them.
Constructor (java.lang.reflect.Constructor) :
 Provides information about, and access to, a single constructor for a class.
Sample Example:
import java.lang.reflect.Constructor;
public class Test {
public Test() {
}
protected Test(int i, double d) {
}
public static void main(String args[]) {
try {
Class cls = Class.forName("Test");


Constructor ctorlist[] = cls.getDeclaredConstructors();
for (int i = 0; i < ctorlist.length; i++) {
Constructor ct = ctorlist[i];
System.out.println("Constructor Name : " + ct.getName());
System.out.println("Declared class : " + ct.getDeclaringClass());
Class pvec[] = ct.getParameterTypes();
for (int j = 0; j < pvec.length; j++)
System.out.println("Argument " + j + " " + pvec[j]);
Class evec[] = ct.getExceptionTypes();
for (int j = 0; j < evec.length; j++)
System.out.println("exc :" + j + " " + evec[j]);
System.out.println("******************");
}
} catch (Throwable e) {
System.err.println(e);
}
}
} 


Output:

Constructor Name : Test
Declared class : class Test
******************
Constructor Name : Test
Declared class : class Test
Argument 0 int
Argument 1 double
******************


Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email