So I've read in some data from an XML:
String arg1Value;
String arg2Value;
String arg2TypeAsString;
String arg1TypeAsString;
and I want to create an object: ObjectType(arg1Type, arg2Type);
I'm trying this:
(ObjectType) Class.forName(arg1TypeAsString).getConstructor(arg1Type.class, arg2Type.class).newInstance(arg1Value, arg2Value)
But this gives me a noSuchMethodException: ObjectType.<init>(arg1Type, arg2Type)
Note that I'm trying to create different objects but they all extend from ObjectType and all their arguments extend from arg1Type and arg2Type respectively.
My initial assumption was that
newInstanceshould be called with array of objects. This is not correct, see comment below. Then likely reason is that you are passing primitive type tonewInstancefor exampleintinstead ofInteger. Naturally creating array of Objects will eliminate such possibility. Finally I managed to replicate error message by removing constructor from my target class so it couldn't be foundPlease take a look at all those exceptions which implementation throws. Please create your
ObjectTypecompile it and place it in classpath so it could be found. Here is my implementation of method returningObjectwhich you can cast to desired typeIt is tested and works. Quite few exceptions to catch. You may want to adjust parameter types so they fit your design requirements. This is my test class