Java Reflection - Class.getDeclaredConstructor() 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> getDeclaredConstructor(Class<?>... parameterTypes)
                                      throws NoSuchMethodException, SecurityException
Parameters:
parameterTypes - the parameter array
Returns:
The Constructor object for the constructor with the specified parameter list


Examples


package com.logicbig.example.clazz;

import java.lang.reflect.Constructor;

public class GetDeclaredConstructorExample {

public GetDeclaredConstructorExample() {
}

public GetDeclaredConstructorExample(int i) {
}

private GetDeclaredConstructorExample(String s) {
}

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

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

cons = c.getDeclaredConstructor(String.class);
System.out.println(cons);
}

}

Output

public com.logicbig.example.clazz.GetDeclaredConstructorExample()
public com.logicbig.example.clazz.GetDeclaredConstructorExample(int)
private com.logicbig.example.clazz.GetDeclaredConstructorExample(java.lang.String)




Inner class's first parameter is of the outer class type (implicitly added during compilation).
See Also: Implicit Outer Class Parameter Tutorial

package com.logicbig.example.clazz;

import java.lang.reflect.Constructor;
import java.util.Arrays;

public class GetDeclaredConstructorExample2 {

public static void main(String... args) throws NoSuchMethodException {
Class<MyClass.TheInnerClass> c = MyClass.TheInnerClass.class;
Constructor<MyClass.TheInnerClass> cons = c.getDeclaredConstructor(MyClass.class, int.class);
System.out.println(cons);
System.out.println(cons.getName());
System.out.println(Arrays.toString(cons.getParameters()));
}

private static class MyClass {
private class TheInnerClass {
private int i;

private TheInnerClass(int i) {
this.i = i;
}
}
}
}

Output

private com.logicbig.example.clazz.GetDeclaredConstructorExample2$MyClass$TheInnerClass(com.logicbig.example.clazz.GetDeclaredConstructorExample2$MyClass,int)
com.logicbig.example.clazz.GetDeclaredConstructorExample2$MyClass$TheInnerClass
[com.logicbig.example.clazz.GetDeclaredConstructorExample2$MyClass arg0, int arg1]




See Also