Get Constructors using Reflection

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

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Pin It on Pinterest

Share This

Share this post with your friends!

Share This

Share this post with your friends!