Private method invoking from outside the class in Java

165 Views Asked by At

I have one class with private method now i want to access that private method outside the class, which is possible using reflection package in java. But what if we make class constructor as private, then how to access that method. In below code consider that PrivateMethodClass is having private method m1 and private constructor.

package allprograms;
import java.lang.reflect.*;
public class RecursionDemo {

    public static void main(String[] args) {

        try 
         {

            PrivateMethodClass p = PrivateMethodClass.getInstance();
            //Class c = Class.forName("allprograms.PrivateMethodClass");  //1 
            Class c = Class.class.asSubclass(p.getClass());
            //Object o = c.newInstance();                                   //2
            Method m = c.getDeclaredMethod("m1", null);                 //3
            m.setAccessible(true);
            m.invoke(p, null);                                          //4

        } /*
             * catch(ClassNotFoundException e) { //for 1
             * System.out.println("ClassNotFound"); }
             */catch (IllegalAccessException/* | InstantiationException */e) { // for 2
            System.out.println("Illigal Access Exception or Instantiation Exception");
        } catch(NoSuchMethodException e) {  //for 3 
            System.out.println("No such Method Exception e");
        } catch(Exception e) {   //for 4
            System.out.println("Invocation Target Exception ");
        }
    }

}
1

There are 1 best solutions below

0
On

I don't understand what your issue is. Static method getInstance() in class PrivateMethodClass is public so no problem to call it, which means it doesn't matter if the constructor of PrivateMethodClass is private or not.

If, on the other hand, you are asking how to instantiate class PrivateMethodClass without using method getInstance(), this is also not a problem. Just as you use getDeclaredMethod() to invoke (private) method m1(), you can call method getDeclaredConstructor() to get a reference to the private constructor. Example code follows:

Class<?> c = PrivateMethodClass.class;
try {
    Constructor<?> ctor = c.getDeclaredConstructor();
    ctor.setAccessible(true);
    Object obj = ctor.newInstance();
    System.out.println(obj);
    if (obj instanceof PrivateMethodClass) {
        PrivateMethodClass p = (PrivateMethodClass) obj;
        Method m = c.getDeclaredMethod("m1");
        m.setAccessible(true);
        m.invoke(p);
    }
}
catch (Exception x) {
    x.printStackTrace();
}

Am I missing something?