Friday, 16 December 2016

Java Reflection

Reflection is the process of Examining or Modifying the run time behaviour of class at run time.
               Class (java.lang,Class) provides many methods to examine or change run time behaviour of class.

Reflection Application -
1.IDE  eg. Eclipse ,Net-Beans etc. 
2.Debugger
3.Test Tools
  
Class "Class" usage -
1.gives methods to get meta-data of Class at runtime.
2.gives methods to examine or change runtime behaviour of class.

How to get Class class object?
1.forName() of class Class
Class c = Class.forName("com.tush.pat.Test");
syso(c.getName());   //prints class name

2.getClass() of Any Object
Simple sm = new Simple();
Class c = sm.getClass();
syso(c.getName());   //prints class name

3..class syntax
  Class c = Simple.class;
  syso(c.getName());   //prints class name

Imp Methods of class Class -
1.newInstance()   -gives new instance of Class

How to get Field ,Constructor and Methods from Class?
Reflection usage Reflect class and Class class. 

       Field f[] = c.getDeclaredFields();
        for(int i=0;i<f.length;i++){
            System.out.println(f[i]);
        }
       
        Method  m[] = c.getDeclaredMethods();
        for(int i=0;i< m.length;i++){
            System.out.println(f[i]);
        }

       
         Constructor c[] = c.getDeclaredMethods();
        for(int i=0;i< c.length;i++){
            System.out.println(f[i]);
        }
 


where Field,Constructor and Method are members of  Reflect class.


How to access Private Fields and Methods in java using reflection ?
As discussed above we can use Reflect and Class classes.
Eg.
public class Simple{
      private void callMe(){
       syso("Hello From Private Method.")
      }
}

public class TestPrivate{
 main(){
          Class c = Class.forName("Simple");
          Object o= c.newInstance();    
          Method m =c.getDeclaredMethod("message"null);   
          m.setAccessible(true); 
          m.invoke(o, null);
      }
}

  same for private members.



 

No comments:

Post a Comment