Ads Sponsored By Google :)

Monday, 28 January 2013

how can|to we finding|find all construtors|parameter type of a class in java with example using reflection API method|construtor


finding constructors in java  finding constructors in java  with example finding constructors in java example
finding constructors in java using reflection API how to find all constructors of a class in java using reflection API how to find all constructors of a class in java how to find all constructors of a class in java using Reflection
finding all constructors of a class in java how can we find constructors of a class in java  how can we find constructors of a class in java using reflection API how can we find constructors of a class and parameter types in java  finding parameter type of constructor in java using reflection how can we find parameter type in java using reflection finding parameter type of method in java using reflection



   Finding Constructors of a class using Reflection:

              Every java class should contain atleast one constructor if we do not add constructor
    in java class then java compiler adds public default constructor into a java class.
        To get constructors META DATA, we need to call getConstructors it  returns an array of  
   type constructor.

    Syntax:
      Constructor cons[]=c.getConstructors();
         Constructor is a class given in java .lang.reflect package. Finding constructor details means in java.lang.reflect package.
       Finding constructor details means finding constructor name and it’s parameter types. To print details of constructors of a class we need an inner loop here an outer loop is used for getting constructor name and inner loop is used for getting parameter types.

     For Example:

    //ReflectDemo4.java
        Class ReflectDemo4
      {
         Class c=Class.forName(args[0]);
        Constructor cons[]=c.getConstructor();
        System.out.println(“Constructors  and parameter types:”);
        for(int i=0;i<cons.length;i++)
       {
          String s1=cons[i].getName();   // finding constructor name
          System.out.println(s1+”(“);
          Class p[]=cons[i].getParameterTypes(); // finding the parameter type of constructor
          for(int j=0;j<p.length;i++)
         {
            String s2=p[j].getName();
           System.out.println(s1+””);
         }
           System.out.println(“)”);
        }
     }

       Analysis:
        From the above program we can understand that finding the constructor name and its 
       parameter types.


      Output:
     
             C:\> javac ReflectDemo4.java java.io.BufferedInputStream
            C:\> java ReflectDemo4

           Constructors and parameter types:
            0-public java.io.BufferedInputStream(java.io.InputStream,int)
            1-public java.io.BufferedInputStream(java.io.InputStream)
           Java.io.InputStream,int


             

No comments:

Post a Comment

LinkWithin