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

前端 未结 2 1465
萌比男神i
萌比男神i 2021-01-20 16:56

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

相关标签:
2条回答
  • 2021-01-20 17:45

    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.

    0 讨论(0)
  • 2021-01-20 17:52

    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);
    
    0 讨论(0)
提交回复
热议问题