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 ");
}
}
}
I don't understand what your issue is. Static method
getInstance()in classPrivateMethodClassis public so no problem to call it, which means it doesn't matter if the constructor ofPrivateMethodClassis private or not.If, on the other hand, you are asking how to instantiate class
PrivateMethodClasswithout using methodgetInstance(), this is also not a problem. Just as you usegetDeclaredMethod()to invoke (private) methodm1(), you can call method getDeclaredConstructor() to get a reference to the private constructor. Example code follows:Am I missing something?