Calling Private Method in Java Class using Reflection API in Java


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);
        m1.setAccessible(true);
        m1.invoke(o,null);//Object,parameter
 
        Method m2=c.getDeclaredMethod("method2",String.class);
        m2.setAccessible(true);
        m2.invoke(o,"Tutor Joes");//Object,parameter
 
 
    }
}
 

Output

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

Basic Programs