Calling Private Method in Java Class using Reflection API in Java

This Java program demonstrates how to access and invoke private methods using reflection. The ReflectDemo class has two private methods method1 and method2. The PrivateReflectionDemo class creates an instance of ReflectDemo and obtains the Class object for it using the getClass() method.

It then obtains a reference to the private method method1 using the getDeclaredMethod() method. Since the method is private, it cannot be accessed directly. To make it accessible, we call the setAccessible(true) method on the Method object. This allows us to call the method using the invoke() method. We pass the object on which the method should be invoked (o in this case) and an array of parameters (in this case, null, since method1 takes no parameters).

The program then does the same thing for the private method method2, which takes a String parameter. We obtain a reference to the method using getDeclaredMethod() and make it accessible using setAccessible(true). We then call the method using invoke() and pass the object on which the method should be invoked (o) and the parameter value ("Tutor Joes").

Note that accessing and invoking private methods using reflection is generally not recommended, as it can lead to unexpected behavior and can be a security risk. It should only be used in cases where there is no other way to achieve the desired functionality.

Source Code

import java.lang.reflect.Method;
class ReflectDemo
    private void method1()
        System.out.println("Method-1 in Private");
    private void method2(String name)
        System.out.println("Method-2 in Private "+name);
public class PrivateReflectionDemo {
    public static void main(String[] args) throws Exception {
        ReflectDemo o =new ReflectDemo();
        Class c=o.getClass();
        Method m1=c.getDeclaredMethod("method1",null);
        Method m2=c.getDeclaredMethod("method2",String.class);
        m2.invoke(o,"Tutor Joes");//Object,parameter


Method-1 in Private
Method-2 in Private Tutor Joes
To download raw file Click Here

Basic Programs