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

}
4

1 回答 1

0

我不明白你的问题是什么。getInstance()类中的静态方法PrivateMethodClass是公共的,因此调用它没有问题,这意味着构造函数是否PrivateMethodClass私有无关紧要。

另一方面,如果您询问如何在PrivateMethodClass 使用方法的情况下实例化类getInstance(),这也不是问题。正如您使用getDeclaredMethod()调用(私有)方法一样m1(),您可以调用方法getDeclaredConstructor()来获取对私有构造函数的引用。示例代码如下:

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

我错过了什么吗?

于 2019-10-26T18:01:49.827 回答