How to call private method from another class in Java with help of Reflection API?
Last Updated :
11 Mar, 2024
We can call the private method of a class from another class in Java (which is defined using the private access modifier
in Java). We can do this by changing the runtime behavior of the class by using some predefined methods of Java. For accessing private methods of different classes we will use Reflection API. To call the private method, we will use the following methods of Java.lang.class and Java.lang.reflect.Method
- Method[] getDeclaredMethods(): This method returns a Method object that reflects the specified declared method of the class or interface represented by this Class object.
- setAccessible(): Set the accessible flag for this object to the indicated boolean value. A value of true indicates that the reflected object should suppress Java language access checking when it is used. A value of false indicates that the reflected object should enforce Java language access checks.
- invoke(): It invokes the underlying method represented by this Method object, on the specified object with the specified parameters.
The below programs demonstrate the calling of private methods in Java:
Example 1: When the name of the private function is known already.
Java
import Java.lang.reflect.Method;
class Check {
private void private_Method()
{
System.out.println( "Private Method "
+ "called from outside" );
}
public void printData()
{
System.out.println( "Public Method" );
}
}
class GFG {
public static void main(String[] args)
throws Exception
{
Check c = new Check();
Method m = Check. class
.getDeclaredMethod( "private_Method" );
m.setAccessible( true );
m.invoke(c);
}
}
|
Output:
Example 2: When the name of private function is not known but class name is known.
Java
import Java.lang.reflect.Method;
class Check {
private void Demo_private_Method()
{
System.out.println( "Private Method "
+ "called from outside" );
}
public void printData()
{
System.out.println( "Public Method" );
}
}
class GFG {
public static void main(String[] args)
throws Exception
{
Check c = new Check();
Method m;
Method method[]
= Check. class .getDeclaredMethods();
for ( int i = 0 ; i < method.length; i++) {
String meth
= new String(method[i].toString());
if (meth.startsWith( "private" )) {
String s = method[i].toString();
int a = s.indexOf( "." );
int b = s.indexOf( "(" );
String method_name = s.substring(a + 1 , b);
System.out.println( "Method Name = "
+ method_name);
m = Check. class .getDeclaredMethod(method_name);
m.setAccessible( true );
m.invoke(c);
}
}
}
}
|
Output:
Share your thoughts in the comments
Please Login to comment...