Java Reflection - Class.getConstructor() Examples

Code Snippets Java Reflection Java 


Class:

java.lang.Class

java.lang.Objectjava.lang.Objectjava.lang.Classjava.lang.Classjava.io.SerializableSerializablejava.lang.reflect.GenericDeclarationGenericDeclarationjava.lang.reflect.TypeTypejava.lang.reflect.AnnotatedElementAnnotatedElementLogicBig

Method:

public Constructor<T> getConstructor(Class<?>... parameterTypes)
                              throws NoSuchMethodException,
                                     SecurityException

This method returns a Constructor object that reflects the specified public constructor of the class represented by this Class object.

Parameters:
parameterTypes - the parameter array
Returns:
the Constructor object of the public constructor that matches the specified parameterTypes


Examples


package com.logicbig.example.clazz;

import java.lang.reflect.Constructor;
import java.math.BigInteger;

public class GetConstructorExample {

public static void main(String... args) throws NoSuchMethodException {
Class<MyClass> c = MyClass.class;
Constructor<MyClass> cons = c.getConstructor();
System.out.println(cons);

cons = c.getConstructor(int.class);
System.out.println(cons);

cons = c.getConstructor(String.class, BigInteger[].class);
System.out.println(cons);
}

private static class MyClass {
public MyClass() {
}

public MyClass(int x) {
}

public MyClass(String s, BigInteger[] integers) {
}
}
}

Output

public com.logicbig.example.clazz.GetConstructorExample$MyClass()
public com.logicbig.example.clazz.GetConstructorExample$MyClass(int)
public com.logicbig.example.clazz.GetConstructorExample$MyClass(java.lang.String,java.math.BigInteger[])




See Also