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.
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.
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.
package reflection;
public class Return {
int price, discount;
private int rate() {
return (price - discount);
}
}
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.
No comments:
Post a Comment