Java.lang Package Classes

Java Class - getDeclaredConstructors() Method



The java.lang.Class.getDeclaredConstructors() method returns an array of Constructor objects reflecting all the constructors declared by the class represented by this Class object. These are public, protected, default (package) access, and private constructors. This method returns an array of length 0 if this Class object represents an interface, a primitive type, an array class, or void.

Syntax

public Constructor<?>[] getDeclaredConstructors()
                                         throws SecurityException

Parameters

No parameter is required.

Return Value

Returns the array of Constructor objects representing all the declared constructors of this class.

Exception

Throws SecurityException, if a security manager, s, is present and any of the following conditions is met:

  • the caller's class loader is not the same as the class loader of this class and invocation of s.checkPermission method with RuntimePermission("accessDeclaredMembers") denies access to the declared constructors within this class.
  • the caller's class loader is not the same as or an ancestor of the class loader for the current class and invocation of s.checkPackageAccess() denies access to the package of this class.

Example:

The example below shows usage of the java.lang.Class.getDeclaredConstructors() method.

import java.lang.*;
import java.lang.reflect.*;

public class MyClass {
  public static void main(String[] args) {
    try {
      Class cls = Class.forName("java.lang.Boolean");

      //print constructors
      Constructor c[] = cls.getDeclaredConstructors();
      System.out.println("Constructors are: ");
      for(Constructor i: c)
        System.out.println(i);
        
    } catch (Exception e) {
      System.out.println(e);
    }
  }
}

The output of the above code will be:

Constructors are: 
public java.lang.Boolean(boolean)
public java.lang.Boolean(java.lang.String)

❮ Java.lang - Class