How to get Class Information with Java Reflection? Interfaces and Super Class

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 only Interfaces and Super Class names.
Spatial Note : I will make a separate class 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. To do that
   1: public class ClassReflector extends BasicItemsComponents{    
   2:     private Class myClass;
   3:     public ClassReflector(Class aClass){
   4:         this();
   5:         myClass = aClass;
   6:     }
   7:     ClassReflector(){//todo for next default initiation 
   8:     }
How to Get Interface Names ?
So, lets have a meted for getting all Interface names which will provide output as string array where every string represent name of the implemented interface.

   1:  public String[] getAllInterfaceNames(){
   2:          String[] interfaces = null;
   3:          int x=0;
   4:          for(Class aClass: this.myClass.getInterfaces())
   5:          {
   6:              interfaces[x]=new String(aClass.getSimpleName());
   7:              x++;
   8:          }
   9:          return interfaces;
  10:      }
How to Get Super Class Name ?
As we know, Java does not support multiple inheritance, so there will be one name. 

   1: public String getParentClassName(){
   2:         return this.myClass.getSuperclass().getName();
   3:     }
 
Thanks ..:)

No comments:

Post a Comment