Get all Constructors in Java



The method java.lang.Class.getConstructors() can be used to return an array that has all the constructor objects that correspond to the public constructors of the class that are represented by the object of the class.

A program that demonstrates this is given as follows −

Example

 Live Demo

package Test;
import java.lang.reflect.*;
public class Demo {
   public static void main(String[] args) {
      try {
         System.out.println("String Constructors are:");
         Constructor c[] = String.class.getConstructors();
         for(int i = 0; i < c.length; i++) {
            System.out.println(c[i]);
         }
      }
      catch (Exception e) {
         System.out.println(e);
      }
   }
}

Output

String Constructors are:
public java.lang.String(byte[],int,int)
public java.lang.String(byte[],java.nio.charset.Charset)
public java.lang.String(byte[],java.lang.String) throws java.io.UnsupportedEncodingException
public java.lang.String(byte[],int,int,java.nio.charset.Charset)
public java.lang.String(byte[],int,int,java.lang.String) throws

java.io.UnsupportedEncodingException
public java.lang.String(java.lang.StringBuilder)
public java.lang.String(java.lang.StringBuffer)
public java.lang.String(byte[])
public java.lang.String(int[],int,int)
java.lang.String()

public java.lang.String(char[])
public java.lang.String(java.lang.String)
public java.lang.String(char[],int,int)
public java.lang.String(byte[],int)
public java.lang.String(byte[],int,int,int)

Now let us understand the above program.

The method getConstructors() is used to obtain all the constructors of the String class. These constructors are stored in the array c[] and then displayed using a for loop. A code snippet which demonstrates this is as follows −

System.out.println("String Constructors are:");
Constructor c[] = String.class.getConstructors();
for(int i = 0; i < c.length; i++) {
   System.out.println(c[i]);
}

Advertisements