How to get all Constructors declared in a Class

Points To Remember
  • We can get the constructors declared in a class using Reflection API.
  • Constructor class is present in java.lang.reflect.Constructor class.
  • The getDeclaredConstructors() method will return an array of Constructors in a class.
Program : Get all constructors declared in a class
import java.lang.reflect.Constructor;


class SampleClass{

 String s1 = "Class variable";
 int a = 123;

 public SampleClass(){
  System.out.println("SampleClass Default Constructor");
 }

 public SampleClass(String str){
  System.out.println("SampleClass Overloaded Constructor");
 }

 public void show(){
  System.out.println("SampleClass Show Method");
 }

 public void print(){
  System.out.println("SampleClass Print Method");
 }

}

class Test{

 public static void main(String args[]){
   Test obj = new Test();
   try{
 Class clazz = Class.forName("SampleClass");
        Constructor cc[] = obj.getConstructors(clazz);
        for(Constructor constructor : cc){
          System.out.println(constructor);
        }
   }catch(Exception e){
 e.printStackTrace();
   }
   
 }

  public Constructor[] getConstructors(Class clazz){
    return clazz.getDeclaredConstructors(); 
 }

}
public SampleClass()
public SampleClass(java.lang.String)
The above example shows how we can get all the constructors that are declared within a class. We first get the Class of the class and then call the getDeclaredConstructors() methods to get an array of all declared constructors.

No comments:

Powered by Blogger.