Search code examples
javamethodhandle

Java MethodHandle api seems to produce incorrect type


Given this code:

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

the NOOP_METHOD produced is

MethodHandle(RulesEngine,DomainObject)void 

Why is that first parameter there, that causes failures when i invoke it, like

mh.invoke(domainObject);

as the error message is:

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

Here is the method in question:

public void noOpRule(DomainObject d) {
}

Solution

  • The method noOpRule is an instance method of the RulesEngine class.

    To call it in regular code, you need a RulesEnigne object as well as a DomainObject object:

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

    To call it through the MethodHandle you need both objects as well:

    mh.invoke(rulesEngine, domainObject);
    

    or, if you are trying to invoking from an instance method of RulesEngine:

    mh.invoke(this, domainObject);