繁体   English   中英

Java反射 - 使用接受接口作为参数的公共构造函数调用受保护的类

[英]Java reflection - Call protected class with public constructor that accepts Interface as argument

我想通过反射调用由公共构造函数组成的受保护类。 以下是我的代码

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 -----^

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM