Close

Java Reflection - Class.getConstructors() Examples

Java Reflection Java Java API 


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<?>[] getConstructors()
                                 throws SecurityException

Returns an array containing Constructor objects reflecting all the public constructors of the class represented by this Class object. An array of length 0 is returned if the class has no public constructors, or if the class is an array class, or if the class reflects a primitive type or void.

Returns:
the array of Constructor objects representing the public constructors of this class


Examples


package com.logicbig.example.clazz;

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

public class GetConstructorsExample {

public static void main(String... args) {
Constructor<?>[] cs = MyClass.class.getConstructors();
Arrays.stream(cs).forEach(System.out::println);
}

private static class MyClass {
public MyClass() {
}

public MyClass(int x) {
}

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

Output

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




package com.logicbig.example.clazz;

import java.lang.reflect.Constructor;

public class GetConstructorsExample2 {

public static void main(String... args) {
Constructor<?>[] cs = int.class.getConstructors();
System.out.println(cs.length);
cs = int[].class.getConstructors();
System.out.println(cs.length);
}
}

Output

0
0




See Also