代码之家  ›  专栏  ›  技术社区  ›  MeBigFatGuy

Java MethodHandle API似乎产生了不正确的类型

  •  0
  • MeBigFatGuy  · 技术社区  · 6 年前

    给定此代码:

    MethodType mt = MethodType.methodType(void.class, DomainObject.class);
    NOOP_METHOD = RULE_METHOD_LOOKUP.findVirtual(RulesEngine.class, "noOpRule", mt);
    

    所产生的noop_方法是

    MethodHandle(RulesEngine,DomainObject)void 
    

    为什么第一个参数会在我调用它时导致失败,比如

    mh.invoke(domainObject);
    

    因为错误消息是:

     java.lang.invoke.WrongMethodTypeException: cannot convert MethodHandle(RulesEngine,DomainObject)void to (DomainObject)void
    

    以下是所讨论的方法:

    public void noOpRule(DomainObject d) {
    }
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   Thomas Kläger    6 年前

    方法 noOpRule RulesEngine 上课。

    要在常规代码中调用它,您需要 RulesEnigne 对象以及 DomainObject 对象:

    public static void callNoOpRule(RulesEngine rulesEngine, DomainObject domainObject) {
        rulesEngine.noOpRule(domainObject);
    }
    

    通过 MethodHandle 您还需要两个对象:

    mh.invoke(rulesEngine, domainObject);
    

    或者,如果您试图从 规则引擎 以下内容:

    mh.invoke(this, domainObject);