0

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 ");
        }
    }

}
  • Have you tried it out? Why not implement it and run and see how it goes? That would help you understand better and also you will never ever forget it :) – Mathews Mathai Oct 26 '19 at 16:50
  • @MathewsMathai I have tried it! I have provide instance of that class using factory method, u can see it in this line //PrivateMethodClass p = PrivateMethodClass.getInstance(); – Viraj Kumbhar Oct 26 '19 at 17:01
  • But this doesnt work further. May be answer to my question is that its impossible to called private method outside if containing class in singleton class – Viraj Kumbhar Oct 26 '19 at 17:02
  • Grab the constructor via [`Class#getDeclaredConstructor`](https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getDeclaredConstructor-java.lang.Class...-), make the constructor accessible & create the instance via [`Constructor#newInstance`](https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Constructor.html#newInstance-java.lang.Object...-) – Vince Oct 26 '19 at 17:07
  • Is static method `getInstance()` in class `PrivateMethodClass` a public method? – Abra Oct 26 '19 at 17:13
  • @VinceEmigh we have object using factory method, now i just want to invoke that private method. – Viraj Kumbhar Oct 26 '19 at 17:29
  • @Abra , it is a static method, as it is a **factory method**. – Viraj Kumbhar Oct 26 '19 at 17:31
  • Yes, `getInstance()` is a static method. That's obvious from the code you posted. What access modifier does the method have? Is it a `public` method? – Abra Oct 26 '19 at 17:36
  • @Abra oops. sorry i didnt get it at first. and yes. it is a public method. – Viraj Kumbhar Oct 26 '19 at 17:44
  • @VinceEmigh, Thank you so much! You already suggested the correct answer ! :) – Viraj Kumbhar Oct 26 '19 at 18:18

1 Answers1

0

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?

Abra
  • 19,142
  • 7
  • 29
  • 41