How do I list the constructors of a class?
Author: Deron Eriksson
Description: This Java tutorial describes how to list the constructors of a class using reflection.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 1.5.4


In JavaSW, if you have a Class object for a particular class, you can obtain its public constructors by calling the getConstructors() method on the class object. If you'd like to get all the constructors (public, protected, and private) of a class, you can call getDeclaredConstructors() on the class object. These methods are demonstrated in the ClassConstructorTest example below.

ClassConstructorTest gets a Class object for the ConstructorTest class. It calls getConstructors() and iterates over the resulting Constructor array of public constructors. ClassConstructorTest then calls getDeclaredConstructors() and iterates over the Constructor array of public, protected, and private constructors.

ClassConstructorTest.java

package test;

import java.lang.reflect.Constructor;

public class ClassConstructorTest {

	public static void main(String args[]) throws Exception {
		Class ctClass = ConstructorTest.class;

		Constructor[] constructors = ctClass.getConstructors();
		for (int i = 0; i < constructors.length; i++) {
			System.out.println("constuctor: " + constructors[i]);
		}

		Constructor[] declaredConstructors = ctClass.getDeclaredConstructors();
		for (int i = 0; i < declaredConstructors.length; i++) {
			System.out.println("declared constructor: " + declaredConstructors[i]);
		}
	}
}

The simple ConstructorTest class is shown below.

ConstructorTest.java

package test;

public class ConstructorTest {

	private String pri;
	protected String pro;
	public String pub;

	private ConstructorTest() {
	}

	public ConstructorTest(String pri, String pro, String pub) {
		this.pri = pri;
		this.pro = pro;
		this.pub = pub;
	}

	public String getPri() {
		return pri;
	}

	public void setPri(String pri) {
		this.pri = pri;
	}

	public String getPro() {
		return pro;
	}

	public void setPro(String pro) {
		this.pro = pro;
	}

	public String getPub() {
		return pub;
	}

	public void setPub(String pub) {
		this.pub = pub;
	}

}

If we execute the ClassConstructorTest class, we see the following:

constuctor: public test.ConstructorTest(java.lang.String,java.lang.String,java.lang.String)
declared constructor: public test.ConstructorTest(java.lang.String,java.lang.String,java.lang.String)
declared constructor: private test.ConstructorTest()

As you can see, getConstructors() retrieves an array of public Constructor objects for a particular class, while getDeclaredConstructors() retrieves an array of public, protected, and private Constructor objects.