//Gets the public constructors
//(except default constructor unless declared explicitly in the class)
Constructor [] constuctors = ConCls.class.getConstructors();
show(constuctors);
System.out.println("##############################");
//Gets all constructors including private constructors
//(except default constructor unless declared explicitly in the class)
constuctors = ConCls.class.getDeclaredConstructors();
show(constuctors);
System.out.println("##############################"); try {
//Can access public constructor
Constructor constructor = ConCls.class.getConstructor(String.class);
System.out.println(constructor);
//We will get java.lang.NoSuchMethodException
//while accessing the following constructors
private static void show(Constructor [] constuctors) {
System.out.println("Total constructors : " + constuctors.length); for (int i = 0 ; i < constuctors.length ; i ++) {
System.out.println(constuctors[i]);
}
}
}
class ConCls { int x; int y;
private ConCls() {
}
ConCls(int x, int y) { this.x = x; this.y = y;
}
protected ConCls(int x) { this(x, x);
}
public ConCls(String x) { this(Integer.parseInt(x));
}
}
It gives the following output,
Total constructors : 1
public com.bethecoder.tutorials.reflection.ConCls(java.lang.String)
##############################
Total constructors : 4
private com.bethecoder.tutorials.reflection.ConCls()
com.bethecoder.tutorials.reflection.ConCls(int,int)
protected com.bethecoder.tutorials.reflection.ConCls(int)
public com.bethecoder.tutorials.reflection.ConCls(java.lang.String)
##############################
public com.bethecoder.tutorials.reflection.ConCls(java.lang.String)