lundi 30 mars 2015

Relfect Constructor's newInstance reports IllegalArgumentException exception

I tried to generate an instance for a dynamically generated class using Reflect Constructor::newInstance. The error and output is:



public TTryCatch(java.lang.invoke.MethodHandle,java.lang.Throwable,java.lang.invoke.MethodHandle)
MethodHandle(List)void class java.lang.Throwable MethodHandle(Throwable,List)void
java.lang.IllegalArgumentException: argument type mismatch
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:68)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:529)
at java.lang.invoke.CatchHandle.getCompiledInstance(CatchHandle.java:188)


My code is:



Class<?> generatedClass = ....;
try {
Constructor constr = generatedClass.getConstructor(MethodHandle.class, Throwable.class, MethodHandle.class);
System.out.println(constr.toString());
System.out.println(tryTarget.toString()+" "+exceptionClass.toString()+" "+ catchTarget.toString());
Object obj = constr.newInstance(tryTarget, exceptionClass, catchTarget);
return obj;
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} ....


The exception shows that the given three parameters for Constructor does not match constructor's parameter's type. It is quite confusing for me because the debug (Also the println result in the output) infor does shows the parameter should be the same.


The generated Constructor method is:



public TTryCatch(java.lang.invoke.MethodHandle, java.lang.Throwable, java.lang.invoke.MethodHandle);
flags: ACC_PUBLIC
Code:


and the given three parameters are: MethodHandle, throwable, and MethodHandle respecively.


Anyone can help to fix my problem? Thanks.






Aucun commentaire:

Enregistrer un commentaire