Sunday, December 14, 2014

Accessing Private Methods and Variables in Java using Reflection API


import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
//Accessing Private methods using Reflection

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

2 comments:

  1. What if constructor is not exposed or overriden.

    ReplyDelete
  2. @Kunal : you can get the constructor and make it accessable true using reflection to navigate that class.
    Reflection provides many ways to expose the constructor like as follows

    Constructor<\A\> constructor = A.class.getDeclaredConstructor();

    constructor.setAccessible(true);

    ReplyDelete

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 ...