Pages

Access Private methods and Fields with Java Reflection

Java Reflection, guess you heard it.But I will give a little bit of introduction and show some code sample to get familiar with this.
OK so the first thing first.
What is Java Reflection ?
Java Reflection can be used to dynamically find java classes , locating and execute methods, access fields at run time.

You can find More on : http://docs.oracle.com/javase/tutorial/reflect/index.html

Here is the sample project that I did.

First I create a class called dynamic test and add one private field and four methods including one private methods. Here is the code and its straight forward.

 package rd.test;  
 public class DynamicTest {  
   private int count;  
   public void printStar() {  
     System.out.println("*");  
   }  
   public void printStarWithInt(int i) {  
     System.out.println("* Integer : " + i);  
   }  
   public void printStarWithString(String param) {  
     System.out.println("* String : " + param);  
   }  
   public void printStarWithStrings(String param1, String param2) {  
     System.out.println("* String : " + param1 + " , and " + param2);  
   }  
   private void printStarInPrivate() {  
     System.out.println("* Private : *");  
   }  
 }  

and here is the class with main method.


 package rd;  
 import rd.test.DynamicTest;  
 import java.lang.reflect.Field;  
 import java.lang.reflect.InvocationTargetException;  
 import java.lang.reflect.Method;  
 public class Main {  
   public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException,  
       InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {  
     Class cls = Class.forName("rd.test.DynamicTest");  
     Object obj = cls.newInstance();  
     /**  
      * calling printstart method without passing any parameters  
      * */  
     Method method = cls.getDeclaredMethod("printStar", null);  
     method.invoke(obj, null);  
     /**  
      * calling printStarWithInt method with int parameter  
      */  
     Class[] intParam = new Class[1];  
     intParam[0] = Integer.TYPE;  
     method = cls.getDeclaredMethod("printStarWithInt", intParam);  
     method.invoke(obj, 100);  
     /**  
      * calling printStarWithStrings methos with two string parameters  
      */  
     Class[] stringParams = new Class[2];  
     stringParams[0]=String.class;  
     stringParams[1]=String.class;  
     method = cls.getDeclaredMethod("printStarWithStrings", stringParams);  
     method.invoke(obj, "hi","rajith");  
     /**  
      * calling private method in DynamicTest class  
      */  
     method = cls.getDeclaredMethod("printStarInPrivate", null);  
     method.setAccessible(true);  
     method.invoke(obj, null);  
     /**  
      * setting and getting private fileds  
      */  
     DynamicTest dynamicTest = new DynamicTest();  
     Field field = cls.getDeclaredField("count");  
     field.setAccessible(true);  
     field.setInt(dynamicTest,10);  
     System.out.println(field.get(dynamicTest));  
   }  
 }  

I explained most of the things with the comments. How to access private fields and methods, how to pass different type of parameters and all.

20 comments:

  1. Excellent post!!! Selenium automation testing tool makes your software validation process lot simpler. Keep on updating your blog with such awesome information. Selenium Training in Chennai | Selenium Course in Chennai | Best Selenium training institute in Chennai

    ReplyDelete
  2. Assam 2564 Police Constable Recruitment 2016 Apply Online


    Your way of describing the whole thing in this paragraph is actually pleasant, every one be able to effortlessly know it, Thanks a lot.........

    ReplyDelete
  3. Latest technology have created a greater impact over testing web applications. This vital in identifying important issues that raises in web appplications. Thanks for sharing this information in here. Keep blogging article like this.

    Selenium training in chennai | Selenium training chennai | Best selenium training in chennai

    ReplyDelete
  4. Thanks for sharing use interview questions on .Net technology. While preparing for my job interview, your article helped me a lot to sharpen my skills and do well in my interview. One of trainer from leading dot net training in Chennai suggests me about your site.

    ReplyDelete
  5. Hello Admin,
    Awesome Post! I like writing style, how you describing the topics throughout the post. I hope many web reader will keep reading your post at the end, Thanks for sharing your view.
    Regards, SAS Training in Chennai

    ReplyDelete
  6. Thanks for sharing detailed information of unified functional testing automation tool. QTP Course in Chennai | QTP training

    ReplyDelete
  7. This wordpress module is made for shippers who need to offer items from their 3dcart Online Store inside their WordPress blog .
    wordpress shop

    ReplyDelete
  8. WoW what a amazing post web page design IN ADDITION TO development solutions AS WELL AS wp-plugins, Android IOS, Android Applications Contact Us

    ReplyDelete
  9. Quite Interesting post!!! Thanks for posting such a useful post. I wish to read your upcoming post to enhance my skill set, keep blogging.
    Regards,
    Software testing training institutes in chennai|Software testing training|Software training

    ReplyDelete
  10. I stand by your thoughts. It is important to make sure that the software application working precisely for the reason it originally designed for. Thus, load testing is mandatory for every application or system before deployment.
    Regards,
    Loadrunner Training in Chennai|hp loadrunner training in chennai|Loadrunner classes in Chennai|loadrunner

    ReplyDelete
  11. Thanks for Sharing the valuable information and thanks for sharing the wonderful article..We are glad to see such a wonderful article..
    QTP Training in Chennai | QTP Training Institute in Chennai | QTP Training

    ReplyDelete

  12. Great content thanks for sharing this informative blog which provided me technical information keep posting.
    Selenium Training in Chennai | Selenium Testing Course in Chennai

    ReplyDelete
  13. I have been reading your blog posts. You blog posts are awesome. They provide good and extremely information which is more valuable. Best Selenium Training in Velachery is predominant famous for Selenium Automation Training and how to get the necessary knowledge about the technology and implement it in a effective way.

    ReplyDelete
  14. Our Android Training in Chennai aims to teach beginners and employees. Android is the fastest growing smart phone OS in the world today. Android Training in Chennai | Android Training in Tambaram | Android Training in Sholinganallur | Android Training in Chennai

    ReplyDelete