从 LambdaMetafactory 创建 BiConsumer

Kri*_*off 3 java reflection method-reference lambda-metafactory

我正在尝试通过 LambdaMetafactory 动态创建 BiConsumer 类型的方法引用。我试图应用在https://www.cuba-platform.com/blog/think-twice-before-using-reflection/上找到的两种方法 - createVoidHandlerLambda 和这里Create BiConsumer as Field setter 而不反映Holger 的答案。

但是在这两种情况下我都遇到以下错误:

Exception in thread "main" java.lang.AbstractMethodError: Receiver class org.home.ref.App$$Lambda$15/0x0000000800066040 does not define or inherit an implementation of the resolved method abstract accept(Ljava/lang/Object;Ljava/lang/Object;)V of interface java.util.function.BiConsumer.
    at org.home.ref.App.main(App.java:20)
Run Code Online (Sandbox Code Playgroud)

我的代码是这样的:

public class App {

    public static void main(String[] args) throws Throwable {
        MyClass myClass = new MyClass();
        BiConsumer<MyClass, Boolean> setValid = MyClass::setValid;
        setValid.accept(myClass, true);

        BiConsumer<MyClass, Boolean> mappingMethodReferences = createHandlerLambda(MyClass.class);
        mappingMethodReferences.accept(myClass, true);
    }

    @SuppressWarnings("unchecked")
    public static BiConsumer<MyClass, Boolean> createHandlerLambda(Class<?> classType) throws Throwable {
        Method method = classType.getMethod("setValid", boolean.class);
        MethodHandles.Lookup caller = MethodHandles.lookup();
        CallSite site = LambdaMetafactory.metafactory(caller,
                "accept",
                MethodType.methodType(BiConsumer.class),
                MethodType.methodType(void.class, MyClass.class, boolean.class),
                caller.findVirtual(classType, method.getName(),
                        MethodType.methodType(void.class, method.getParameterTypes()[0])),
                MethodType.methodType(void.class, classType, method.getParameterTypes()[0]));

        MethodHandle factory = site.getTarget();
        return (BiConsumer<MyClass, Boolean>) factory.invoke();
    }

    public static <C, V> BiConsumer<C, V> createSetter(Class<?> classType) throws Throwable {
        Field field = classType.getDeclaredField("valid");
        MethodHandles.Lookup lookup = MethodHandles.lookup();
        final MethodHandle setter = lookup.unreflectSetter(field);
        final CallSite site = LambdaMetafactory.metafactory(lookup,
                "accept", MethodType.methodType(BiConsumer.class, MethodHandle.class),
                setter.type().erase(), MethodHandles.exactInvoker(setter.type()), setter.type());
        return (BiConsumer<C, V>)site.getTarget().invokeExact(setter);
    }

}
Run Code Online (Sandbox Code Playgroud)

MyClass 看起来像这样:

public class MyClass {

    public boolean valid;

    public void setValid(boolean valid) {
        this.valid = valid;
        System.out.println("Called setValid");
    }
}
Run Code Online (Sandbox Code Playgroud)

我将不胜感激您在这方面的帮助。

编辑#1。咨询@Holger后,我将 createSetter 方法修改为:

@SuppressWarnings("unchecked")
    public static <C, V> BiConsumer<C, V> createSetter(Class<?> classType) throws Throwable {
        Field field = classType.getDeclaredField("valid");
        MethodHandles.Lookup lookup = MethodHandles.lookup();
        final MethodHandle setter = lookup.unreflectSetter(field);
        MethodType type = setter.type();
        if(field.getType().isPrimitive())
            type = type.wrap().changeReturnType(void.class);
        final CallSite site = LambdaMetafactory.metafactory(lookup,
                "accept", MethodType.methodType(BiConsumer.class, MethodHandle.class),
                type.erase(), MethodHandles.exactInvoker(setter.type()), type);
        return (BiConsumer<C, V>)site.getTarget().invokeExact(setter);
    }
Run Code Online (Sandbox Code Playgroud)

现在这个方法不会抛出初始异常,尽管对此方法引用调用accept似乎没有效果。我在这次通话的日志中没有看到“Called setValid”。仅适用于 MyClass::setValid;

Hol*_*ger 6

请注意,对同一方法使用getMethod和是多余的。caller.findVirtual(\xe2\x80\xa6)如果您的起点是 a Method,您可以使用unreflect,例如

\n\n
Method method = classType.getMethod("setValid", boolean.class);\nMethodHandles.Lookup caller = MethodHandles.lookup();\nMethodHandle target = caller.unreflect(method);\n
Run Code Online (Sandbox Code Playgroud)\n\n

当您动态发现方法和/或在流程中寻找其他工件(例如注释)时,这可能很有用。否则,只需获得过MethodHandlefindVirtual就足够了。

\n\n

然后,您必须了解三种不同的函数类型:

\n\n
    \n
  • 目标方法句柄具有特定类型,该类型在将方法句柄传递给工厂时隐式给出。在你的情况下,它是(MyClass,boolean)\xc2\xa0\xe2\x86\x92\xc2\xa0void
  • \n
  • 与预期结果类型
    \n关联的通用函数类型BiConsumer<MyClass, Boolean>,即(MyClass,Boolean)\xc2\xa0\xe2\x86\x92\xc2\xa0void
  • \n
  • 接口的擦除类型BiConsumer,即(Object,Object)\xc2\xa0\xe2\x86\x92\xc2\xa0void
  • \n
\n\n

只有正确指定所有三种类型才告诉工厂它必须使用代码实现方法
\n ,void accept(Object,Object)该代码将第一个参数转换为 ,将MyClass第二个Boolean参数转换为 ,然后将第二个参数解包为boolean,最终调用目标方法。

\n\n

我们可以显式指定类型,但为了使代码尽可能可重用,我们可以调用type()目标,然后使用适配器方法。

\n\n
    \n
  • wrap()会将所有原始类型转换为其包装类型。不幸的是,这也意味着将返回类型转换为Void,因此我们必须再次将其设置回void
    \n这给了我们instantiatedMethodType参数。(与文档比较)
  • \n
  • erase()会将所有引用类型转换为原始类型,Object但保留所有原始类型不变。因此,将其应用于instantiatedMethodType 会得到擦除的类型。
    \n这个简单的转换是否足够取决于特定的目标接口。对于 中的接口来说java.util.function,确实如此。
  • \n
\n\n

提高可重用性的另一点是为方法接收者类使用实际类型参数,因为无论如何我们都会将该类作为参数:

\n\n
public static <T>\n       BiConsumer<T, Boolean> createHandlerLambda(Class<T> classType) throws Throwable {\n\n    MethodHandles.Lookup caller = MethodHandles.lookup();\n    MethodHandle target = caller.findVirtual(classType, "setValid",\n        MethodType.methodType(void.class, boolean.class));\n    MethodType instantiated = target.type().wrap().changeReturnType(void.class);\n\n    CallSite site = LambdaMetafactory.metafactory(caller,\n            "accept", MethodType.methodType(BiConsumer.class),\n            instantiated.erase(), target, instantiated);\n    return (BiConsumer<T, Boolean>)site.getTarget().invoke();\n}\n
Run Code Online (Sandbox Code Playgroud)\n