[英]Why do I get a WrongMethodTypeException on invokeExact even though MethodHandle is OK
[英]Why a WrongMethodTypeException from MethodHandle? Is my object type incorrect?
我在尝试将我的事件系统从反射切换到 MethodHandle 时遇到了问题。
我正在使用 KyoriPowered 在 Github ( https://github.com/KyoriPowered/event ) 上的事件总线(版本 3.0.0)。
我的代码如下:
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
}
}
}
}
我希望这能正常工作,但结果是:
java.lang.invoke.WrongMethodTypeException:无法将 MethodHandle(,UserOnlineEvent)void 转换为 (Event)void
UserOnlineEvent 是测试中使用的事件类型。
问题是我无法获得事件的真实类型。
编辑:这个问题已经解决。 我应该使用两个 arguments。只需将侦听器添加为 handle.invoke 的第一个参数,它就可以工作。
根据你的消息,我在JDK中找到了代码。 在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);
}
很明显,我猜参数类型是错误的。 如果调试,你会发现它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.