Java Reflection - Class.getDeclaredConstructors() 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<?>[] getDeclaredConstructors()
                                         throws SecurityException
Returns:
the array of Constructor objects representing all the declared constructors of this class.


Examples


package com.logicbig.example.clazz;

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

public class GetDeclaredConstructorsExample {
public GetDeclaredConstructorsExample() {
}

public GetDeclaredConstructorsExample(int i) {
}

private GetDeclaredConstructorsExample(String s) {
}

public static void main(String... args) {
Constructor<?>[] cons = GetDeclaredConstructorsExample.class.getDeclaredConstructors();
Arrays.stream(cons).forEach(System.out::println);

}
}

Output

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




package com.logicbig.example.clazz;

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

public class GetDeclaredConstructorsExample2 {

public static void main(String... args) {
Constructor<?>[] cons = MyClass.TheInnerClass.class.getDeclaredConstructors();
Arrays.stream(cons).forEach(con -> {
System.out.println("name: " + con.getName());
Arrays.stream(con.getParameters()).forEach(System.out::println);
});
}

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

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

Output

name: com.logicbig.example.clazz.GetDeclaredConstructorsExample2$MyClass$TheInnerClass
com.logicbig.example.clazz.GetDeclaredConstructorsExample2$MyClass arg0
int arg1




See Also