我想通过反射调用一个包含公共构造函数的受保护类。以下是我的代码

final Class clazz = Whitebox.getInnerClassType(parentClass.getClass(),
"InnerClassName");
final Constructor constructor = Whitebox.getConstructor(clazz,AnInterface.class);
obj = constructor.newInstance(interfaceMockObject);


我得到以下异常:

org.powermock.reflect.exceptions.ConstructorNotFoundException: Failed to lookup constructor with parameter types


我认为问题可能出在构造函数参数是一个接口上。

最佳答案

内部类隐式地将封闭对象作为其构造函数的第一个参数。使用反射时,您需要明确指定它:

final Class clazz = Whitebox.getInnerClassType(parentClass.getClass(), "InnerClassName");
final Constructor constructor =
     Whitebox.getConstructor(clazz, paretnClass.getClass(), AnInterface.class);
     // Here -----------------------^

statusPage = constructor.newInstance(parentClass, interfaceMockObject);
// And pass the parent instance -----^

09-04 05:45
查看更多