Tech Me More

To quench our thirst of sharing knowledge about our day to day experience & solution to techincal problems we face in our projects.

Advertise with us !
Send us an email at

Monday, March 2, 2015

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

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);

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: