简体   繁体   中英

Why a WrongMethodTypeException from MethodHandle? Is my object type incorrect?

I have encountered a problem while I am trying to switch my event system from reflection to MethodHandle.

I am using an event bus (version 3.0.0) by KyoriPowered on Github ( https://github.com/KyoriPowered/event ).

My code is following:

public class EventExecutorFactory implements EventExecutor.Factory<Event, Listener> {
    @Override
    public @NonNull EventExecutor<Event, Listener> create(@NonNull Object object, @NonNull Method method) throws Exception { // object is Listener
        method.setAccessible(true);
        Class<? extends Event> actualEventType = method.getParameterTypes()[0].asSubclass(Event.class);
        MethodHandle handle = MethodHandles.lookup().unreflect(method);
        return new EventExecutor<Event,Listener>() {

            @Override
            public void invoke(@NonNull Listener listener, @NonNull Event event) throws Throwable {
                if (!actualEventType.isInstance(event)) return; // many different event types defined in my system, so I should check it first.
                handle.invoke(actualEventType.cast(event)); // WrongMethodTypeException thrown here
            }
        }
    }
}

I expected this to work fine, but the result is:

java.lang.invoke.WrongMethodTypeException: cannot convert MethodHandle(,UserOnlineEvent)void to (Event)void

UserOnlineEvent is the event type that used in test.

The problem is that I cannot get the real type of the event.


Edit: This problem has been solved. I should use two arguments. just add the listener as the first argument to handle.invoke, and it works.

According to your message, I find the code in JDK. at MethodHandle#asTypeUncached

/*non-public*/ 
MethodHandle asTypeUncached(MethodType newType) {
        if (!type.isConvertibleTo(newType))
            throw new WrongMethodTypeException("cannot convert "+this+" to "+newType);
        return asTypeCache = MethodHandleImpl.makePairwiseConvert(this, newType, true);
    }

it's clear, I guess parameter type is wrong. if debug, you will find it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM