I have spend whole day on this problem. My problem is how to make an MethodHandle.invokeExact invocation on an instance, whose class type is dynamically loaded at program ru
To make sense, you'll have to type the method ( otherwise the cast is pointless):
public <T> void doSomething() {
BaseTemplate obj = ...
Class<T> newType = Class('AddSample');
T t = newType.cast(obj);
Without the method typing, you can't tie the dynamic class to the type to be cast to.
You can’t use invokeExact
if the compile-time type of an argument doesn’t match the MethodHandle
’s parameter type. It doesn’t help to play around with the Generic constructs like invoking cast
on a Class<T>
, the dynamic type is still unknown to the compiler.
Or, in other words, due to type erasure, the type of tObj
is still Object
on the byte code level. And this is the “invoked type” of the MethodHandle
.
The simplest solution is to use invoke
rather than invokeExact
.
The only thing you can do if you want to use invokeExact
, is to transform the MethodHandle
to the type which you will eventually invoke, i.e. change the type of the first parameter to Object
:
myMH=myMH.asType(myMH.type().changeParameterType(0, Object.class));
// now it doesn’t matter that obj has compile-time type Object
assertEquals((int)myMH.invokeExact(obj, "addintaasdsa", 10, 20.0f), 12);