Get Constructors Reflection API Java


It is advised to read the notes on Java Reflection API before attempting the programs.

Example on Get Constructors
import java.lang.reflect.Constructor;	
public class Demo extends Test
{
  public Demo()  {  }
  public Demo(int x)  {  }
  protected Demo(int x, int y)  {  }
  public static void main(String args[])
  {
     Demo d1 = new Demo();
     Class c = d1.getClass();

     System.out.println("Following are public constructors:");
     Constructor con[ ] = c.getConstructors();
     for(int i = 0; i < con.length; i++) 
     {
        System.out.println(con[i].getName());     //  Demo,                                 
     }

     System.out.println("\nFollowing are all constructors of any specifier:");        
     Constructor dcon[] = c.getDeclaredConstructors();
     for(int i = 0; i < dcon.length; i++)
     { 
        System.out.println(dcon[i].getName()) ;                  
     }   // all the constructors are displayed
   }
}

getConstructors() returns only public constructors.

getDeclaredConstructors() returns all constructors of any access specifier.

Leave a Comment

Your email address will not be published.