Monday, March 2, 2015

How to access the private method of a class outside of the class in Java. [Reflection]

2:35 PM

How to access the private method of a class in other class. For example check the below class Return , it has a private method rate(). How to access method rate() outside of class Return.


package reflection;

public class Return {
 int price, discount;

 private int rate() {
  return (price - discount);
 }
}



Although, private methods are meant to be accessed in the same class they are declared and when we try to access it outside of the declared class it gives a compile time error. But Reflection API of java provides a way to access private method outsides of class. 

Check the below code which access the rate() method of Return class in Test class.


package reflection;

import java.lang.reflect.Method;

class Test {
 public static void main(String[] args) throws Exception {
  Return p = new Return();
  Method m = p.getClass().getDeclaredMethod("rate", null);
  m.setAccessible(true);
  System.out.println(m.invoke(p));
 }
}



Under the hood - no private stuff is actually private.

Thus, the field or method can be accessed.
In byte code - there is a flag which is byte code level implementation of private-ness.

0 comments :

Post a Comment

 

© 2014 DieHardTechy . All rights resevered. Designed by Diehardtechy