编程语言
首页 > 编程语言> > java – 将MethodHandle转换为方法引用(此处为Function)

java – 将MethodHandle转换为方法引用(此处为Function)

作者:互联网

MethodType methodType = MethodType.methodType(void.class, ByteBuffer.class);
MethodHandle handle = MethodHandles.publicLookup().findConstructor(type, methodType);

Function<ByteBuffer, Object> = handle; // ???

是否有可能让最后的作业有效?倒置方式不起作用:Is it possible to convert method reference to MethodHandle?

这是另一个可复制的例子:

new Integer("123");

MethodType methodType = MethodType.methodType(void.class, String.class);
MethodHandle handle = MethodHandles.publicLookup().findConstructor(Integer.class, methodType);

Function<String, Integer> function1 = Integer::new;
Function<String, Integer> function2 = handle.toLambda(); // ???

解决方法:

«This answer»包含一个代码示例,演示如何使用相同的功能将MethodHandle转换为功能接口实现,Java 8的lambda表达式和方法引用使用.

这都是关于使用方法句柄调用LambdaMetafactory.metafactory,所需的接口以及唯一抽象方法和所需签名的名称.

method’s documentationit’s class documentation都非常详细.

因此,对于您的请求,示例代码可能如下所示:

MethodType methodType = MethodType.methodType(Integer.class, String.class);
MethodHandles.Lookup lookup = MethodHandles.lookup();
MethodHandle handle = lookup.findStatic(Integer.class, "valueOf", methodType);
Function<String,Integer> f=(Function<String,Integer>)
  LambdaMetafactory.metafactory(lookup, "apply",
    MethodType.methodType(Function.class), methodType.generic(),
    handle, methodType).getTarget().invokeExact();

System.out.println(f.apply("123"));

你必须在这里关心签名类型.第四个参数samMethodType是指原始接口的功能签名的方法类型,因此对于原始类型Function,我们必须实现Object apply(Object),而instantiatedMethodType描述方法Integer apply(String).这就是为什么在methodType上为第四个参数调用方法.generic(),它将(String)Integer转换为(Object)Object.

这对于构造函数来说甚至更棘手,因为构造函数将使用(String)void类型查找,而函数类型与静态方法情况相同.因此,对于静态方法,方法的MethodType与MethodType匹配,而对于构造函数,我们必须使用不同的类型进行查找:

MethodType methodType = MethodType.methodType(Integer.class, String.class);
MethodHandles.Lookup lookup = MethodHandles.lookup();
MethodHandle handle = lookup.findConstructor(
        Integer.class, MethodType.methodType(void.class, String.class));
Function<String,Integer> f=(Function<String,Integer>)
  LambdaMetafactory.metafactory(lookup, "apply",
    MethodType.methodType(Function.class), methodType.generic(),
    handle, methodType).getTarget().invokeExact();

但这只是为了完整性,对于Integer类型,你不应该调用构造函数,而是使用valueOf方法,最好是.

标签:java,java-8,lambda,reflection,invokedynamic
来源: https://codeday.me/bug/20191006/1860336.html