How to get all Constructor information under a Class in Java Reflection?

This is continuing article of my previous post. In this article we will see how can we retrieve Class Related Information using Java Reflection .We will see Constructor Names .

Spatial Note : I will make a separate reflector utility class where we input a target class in its constructor and we will retrieve information using separate method. In this way ,we can isolate our needs. Please see this before start.

How to get all Constructors of a class?
This is very simple, unlike the method, a class has only its own constructors so, we can have direct access.
   1: public String[] getAllConstructorNames(){
   2:         ArrayList<String> allConstructors = new ArrayList<String>();
   3:         for(Constructor aConstructor: myClass.getDeclaredConstructors()){
   4:         allConstructors.add("Constructor Name : " 
+aConstructor.getName()+" , Full Name : "+aConstructor.toString());
   5:         }
   6:         return allConstructors.toArray(new String[allConstructors.size()]);
   7:     }
How to get only Public Constructors of a class?
In this way we can see only public constructors.
   1: public String[] getAllPublicConstructorNames(){
   2:         ArrayList<String> allConstructors = new ArrayList<String>();
   3:         for(Constructor aConstructor: myClass.getConstructors()){
   4:         allConstructors.add("Constructor Name : "
 +aConstructor.getName()+" , Full Name : "+aConstructor.toString());
   5:         }
   6:         return allConstructors.toArray(new String[allConstructors.size()]);    
   7:     }
Like as filed and method cases, we can get access using parameter names. like as follows.
myClass.getConstructor(<Parameters>);
myClass.getDeclaredConstructor(<Paraeters>);
I will provide separate post for calling and manipulating those constructors.

Thanks..:)

No comments:

Post a Comment