Despite the common belief it is actually possible to access Private methods and fields from other class. This can be achieved using Java Reflection. It is not even that difficult but this only works as a Standalone Java applications.
Using Java Reflection one can examine or modify the run time behavior of a class at run time. The java.lang and java.lang.reflect provides classes for Java Reflection.
Now we'll see how to access Private Methods and Fields from other class. By the help of java.lang.Class class and java.lang.reflect.Method class we can call the private methods from any other class. Similarly by using java.lang.reflect.Field class we can accessing Private Fields from any other class.
To access private methods, following methods are required -
1. getDeclaredMethod() method of Class class
2. setAccessible() and invoke() methods of Method class
And to access private fields, following methods are required -
1. getDeclaredField() method of Class class
2. get() method of Field class
Let us see and example -
package com.anjan.privat;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
class MyPrivateClass{
private int value = 10;
private void printPrivate(){
System.out.println("Private Method");
}
private void multiply(int a, int b){
System.out.println("Product of "+a+" and "+b+" is "+a*b);
}
}
public class PrivateMethodDemo {
public static void main(String args[])throws Exception{
Class cl = Class.forName("com.anjan.privat.MyPrivateClass");
Object obj = cl.newInstance();
//Accessing Private Method without parameter
Method method = cl.getDeclaredMethod("printPrivate", null);
method.setAccessible(true);
method.invoke(obj, null);
//Accessing Private Method with parameter
method = cl.getDeclaredMethod("multiply", new Class[]{int.class, int.class});
method.setAccessible(true);
method.invoke(obj, 3, 4);
//Accessing Private Field
Field field = cl.getDeclaredField("value");
field.setAccessible(true);
System.out.println("Value of private field : "+field.get(obj));
}
}
Output -
Private Method
Product of 3 and 4 is 12
Value of private field : 10
Similarly we can access Private Classes and Private Constructors as well in Java using Java Reflection.