gpt4 book ai didi

java - 将 LambdaMetafactory.metafactory() 用于普通的非静态 getter

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:33:40 25 4
gpt4 key购买 nike

我有一个简单的 Person 类,它有一个返回 StringgetName():

public class Person {

public String getName() {...}

}

如何在运行时使用 LambdaMetafactory 为非静态方法 getName() 创建 lambda?

这是到目前为止我得到的结果:

public class MyMain {

public static void main(String[] args) throws Throwable {
GetterFunction getterFunction;

MethodHandles.Lookup lookup = MethodHandles.lookup();
String invokedMethodName = "getName";
MethodType invokedType = MethodType.methodType(GetterFunction.class);
MethodType methodType = MethodType.methodType(Object.class);
MethodHandle virtual = lookup.findVirtual(Person.class, "getName", MethodType.methodType(String.class));
CallSite site = LambdaMetafactory.metafactory(lookup,
invokedMethodName,
invokedType,
methodType,
virtual,
methodType);
getterFunction = (GetterFunction) site.getTarget().invokeExact();
System.out.println(getterFunction.getName(new Person("Ann")));
}

@FunctionalInterface
private interface GetterFunction {

String getName(Person person);

}

}

抛出:

java.lang.invoke.LambdaConversionException: Incorrect number of parameters for instance method invokeVirtual foo.Person.getName:()String; 0 captured parameters, 0 functional interface method parameters, 0 implementation parameters
at java.lang.invoke.AbstractValidatingLambdaMetafactory.validateMetafactoryArgs(AbstractValidatingLambdaMetafactory.java:193)
at java.lang.invoke.LambdaMetafactory.metafactory(LambdaMetafactory.java:303)

最佳答案

只是扩展了 Geoffrey De Smet 的回答,以展示使用 Function 会是什么样子,因为需要进行一些小的调整:

public class MyMain {

public static void main(String[] args) throws Throwable {
MethodHandles.Lookup lookup = MethodHandles.lookup();
CallSite site = LambdaMetafactory.metafactory(lookup,
"apply",
MethodType.methodType(Function.class),
MethodType.methodType(Object.class, Object.class), // Function::apply signature
lookup.findVirtual(Person.class, "getName", MethodType.methodType(String.class)),
MethodType.methodType(String.class, Person.class) // Person::getName signature
);

Function<Person, String> getterFunction = (Function<Person, String>) site.getTarget().invokeExact();

System.out.println(getterFunction.apply(new Person("Ann")));
}

static class Person {
String name;

public Person(String name) {
this.name = name;
}

public String getName() {
return name;
}
}

}

关于java - 将 LambdaMetafactory.metafactory() 用于普通的非静态 getter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48203370/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com