1

我正在尝试通过 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)

我的代码是这样的:

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);
    }

}

MyClass 看起来像这样:

public class MyClass {

    public boolean valid;

    public void setValid(boolean valid) {
        this.valid = valid;
        System.out.println("Called setValid");
    }
}

我将感谢您对此的帮助。

编辑#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);
    }

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

4

1 回答 1

4

请注意,您对同一方法使用getMethodandcaller.findVirtual(…)是多余的。如果您的起点是 a Method,您可以使用unreflect,例如

Method method = classType.getMethod("setValid", boolean.class);
MethodHandles.Lookup caller = MethodHandles.lookup();
MethodHandle target = caller.unreflect(method);

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

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

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

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

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

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

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

public static <T>
       BiConsumer<T, Boolean> createHandlerLambda(Class<T> classType) throws Throwable {

    MethodHandles.Lookup caller = MethodHandles.lookup();
    MethodHandle target = caller.findVirtual(classType, "setValid",
        MethodType.methodType(void.class, boolean.class));
    MethodType instantiated = target.type().wrap().changeReturnType(void.class);

    CallSite site = LambdaMetafactory.metafactory(caller,
            "accept", MethodType.methodType(BiConsumer.class),
            instantiated.erase(), target, instantiated);
    return (BiConsumer<T, Boolean>)site.getTarget().invoke();
}
于 2020-05-04T14:40:47.863 回答