Java examples on java.lang.reflect
- How do I invoke a method using Method class?
- How do I get field of a class object and set or get its value?
- How do I get fields of a class object?
- How do I get the methods of a class object?
- How do I create object using Constructor object?
- How do I determine if a class object represents an array class?
- How do I get constructors of a class object?
- How do I get modifiers of a class object?
- How do I get information regarding class name?
- How do I get the component type of an array?
- How do I get direct superclass and interfaces of a class?
- How do I check if a class represent a primitive type?
- How do I check if a class represent an interface type?
How do I get constructors of a class object?
Below is an example that showing you how to get constructors of a class object. In the code below we get the constructors by calling the Class.getDeclaredConstructors() or the Class.getConstructor(Class[]) method.
package org.kodejava.example.reflect;
import java.lang.reflect.Constructor;
public class GetConstructors {
public static void main(String[] args) {
Class clazz = String.class;
//
// Get all declared contructors and iterate the constructors to get their
// name and parameter types.
//
Constructor[] constructors = clazz.getDeclaredConstructors();
for (Constructor constructor : constructors) {
String name = constructor.getName();
System.out.println("Constructor name= " + name);
Class[] paramterTypes = constructor.getParameterTypes();
for (Class c : paramterTypes) {
System.out.println("Param type name = " + c.getName());
}
System.out.println("----------------------------------------");
}
//
// Getting a specific constructor of the java.lang.String
//
try {
Constructor constructor = String.class.getConstructor(new Class[] {String.class});
System.out.println("Constructor = " + constructor.getName());
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
}