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