Sunday, April 10, 2011

Accessing Private Methods and Variables in Java


import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
//Accessing Private methods using Reflection******************Fields can be also used
//in the same Way*********************************************
public class Test {
 public static void main(String ag[])
 {
  A obj=new A();

  try {
   Class c=obj.getClass();
   Method method=c.getDeclaredMethod("msg", null);
   //System.out.println(method);
   try {
 
    method.setAccessible(true);
    method.invoke(obj,null);//Calling Private method of a class.
 
   } catch (IllegalArgumentException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } catch (IllegalAccessException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } catch (InvocationTargetException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  } catch (SecurityException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (NoSuchMethodException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }


 }
}
////////////second class************Having Private methods
class A
{
 private void msg()
 {
  System.out.println("In class A of private Mehod");
 }
}


//Hi Guys we can access the private fields of a java class using reflection in the same way.
Thanks
Pankaj Kumar Singh

No comments:

Post a Comment

Spring Boot Config Server and Config Client.

 In Spring cloud config we can externalise our configuration files to some repository like GIT HUT, Amazon S3 etc. Benefit of externalising ...