dimanche 11 décembre 2022

Java 8: 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 everything works fine.

But the result is:

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

UserOnlineEvent is the event type that used in test.

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





Aucun commentaire:

Enregistrer un commentaire