我正在尝试在 RCP 插件项目中使用 java.lang.reflect 方法来创建对象的新实例。如果我使用这个:
constructorList[0].newInstance();
它在运行时运行良好(通过 RCP 应用程序运行),但该代码行在 JUnit 中失败,并显示:java.lang.IllegalArgumentException:参数数量错误
如果我用这个代替:
constructorList[0].newInstance(((Object) null));
运行 JUnit 工作正常,但在运行时失败:java.lang.IllegalArgumentException:参数数量错误
唯一的区别似乎是插件中运行的代码与独立 JUnit 中运行的代码。 有谁知道这是否可能是根本原因?我不确定如何设置 JUnit 作为 JUnit 插件运行,因此我无法对其进行测试。
newInstance 方法的 JavaDoc:
...
If the number of formal parameters required by the underlying constructor * is 0, the supplied
initargs
array may be of length 0 or null.@param initargs array of objects to be passed as arguments to * the constructor call; values of primitive types are wrapped in * a wrapper object of the appropriate type (e.g. a float * in a {@link java.lang.Float Float})
...
最佳答案
老实说,我能想到的唯一解释是,在这些情况下,您以某种方式加载了该类的两个不同版本(这并不像听起来那么牵强,因为 Eclipse RCP 使用 OSGi,它在类加载方面做了一些技巧)。如果该类没有声明的构造函数并且不是内部类,则 constructorList[0].newInstance(((Object) null))
在任何情况下都不应工作。
关于java - Constructor.newInstance() 在 JUnit 中与实际运行时的行为不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37211405/