有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java构造函数。newInstance()在JUnit和实际运行时中的行为不同

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

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

...


共 (1) 个答案

  1. # 1 楼答案

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