Constructor.newInstance() 在 JUnit 中的行为与实际运行时不同

Constructor.newInstance() behaving differently in a JUnit vs actual runtime

我正在尝试使用 java.lang.reflect 方法在 RCP 插件项目中创建对象的新实例。如果我使用这个:

constructorList[0].newInstance();

它在 运行 时间内工作正常,(运行 通过 RCP 应用程序),但代码行在 JUnit 中失败:java.lang.IllegalArgumentException: wrong number of arguments

如果我改用这个:

constructorList[0].newInstance(((Object) null));

它在 JUnit 运行 中工作正常,但在 运行 时间内失败:java.lang.IllegalArgumentException: wrong number of arguments

唯一的区别似乎是 运行插件中的代码与独立的 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})

...

老实说,我能想到的唯一解释是,在这些情况下,您以某种方式加载了 class 的两个不同版本(这并不像听起来那么牵强,因为 Eclipse RCP 使用 OSGi,这对 classloading 做了一些技巧)。如果 class 没有声明的构造函数并且不是内部 class,那么 constructorList[0].newInstance(((Object) null)) 在任何情况下都不应该工作。