Neil P.
Neil P.

Reputation: 1114

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

I'm trying to use java.lang.reflect methods, in a RCP plug-in project to create a new instance of an object. If I use this:

constructorList[0].newInstance();

It works fine during runtime, (Running through the RCP App), but the line of code fails in a JUnit with: java.lang.IllegalArgumentException: wrong number of arguments

If I use this instead:

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

It works fine running the JUnit, but fails with during runtime with: java.lang.IllegalArgumentException: wrong number of arguments

The only difference seems to be the code running within a plug-in vs a standalone JUnit. Does anyone know if this would probably be the root cause? I'm not sure on how to setup my JUnit to run as a JUnit Plug-in, so I haven't been able to test it out.

The JavaDoc for the newInstance method:

...

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

...

Upvotes: 1

Views: 198

Answers (1)

Alexey Romanov
Alexey Romanov

Reputation: 170835

Honestly, the only explanation I can think of is that you somehow are loading two different versions of the class in these cases (this isn't as farfetched as it sounds, because Eclipse RCP uses OSGi, which does some tricks with classloading). If the class has no declared constructors and isn't an inner class, constructorList[0].newInstance(((Object) null)) shouldn't work in any circumstances.

Upvotes: 2

Related Questions