Error: you call the wrong constructor - and the compiler cannot help you.
The problem you are facing is that you were accessing the constructor with a null argument, not the argument with the arguments. Remember that constructors in java are ultimately just methods, albeit special ones - and with reflection all bets are disabled --- the compiler will not help you if you do something stupid. In your case, you had a problem with the scope, as well as a problem with the method signature at the same time.
How to solve this problem and NEVER have to deal with it again in this application
It is a good idea to wrap the constructor calls in a static helper method that can be directly tested and then explicitly test them in my unit tests, because if the constructor changes and you forget to update the reflection code, you will again see that these critical errors are creeping again.
You can also just call the constructor as follows:
public static Child create(Integer i, String s) throws Exception { Constructor c = Class.forName(childClass).getConstructor(new Object[]{Integer.class, String.class}); c.setAccessible(true); Child instance = (Child) c.newInstance(new Object[]{i , s}) ; return instance; }
and of course add to your tests
@Test public void testInvoke() { try{ MyClass.create(1,"test"); } catch(Exception e) { Assert.fail("Invocation failed : check api for reflection classes in " + MyClass.class); } }
source share