InvokeExact on the object, whose type is dynamically loaded by classloader

十年热恋 提交于 2019-12-01 22:38:10

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!