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

MethodType methodType = MethodType.methodType(void.class, ByteBuffer.class);

MethodHandle handle = MethodHandles.publicLookup().findConstructor(type, methodType);

Function = handle; // ???

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

new Integer("123");

MethodType methodType = MethodType.methodType(void.class, String.class);

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

Function function1 = Integer::new;

Function function2 = handle.toLambda(); // ???

解决方法:

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

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

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

MethodType methodType = MethodType.methodType(Integer.class, String.class);

MethodHandles.Lookup lookup = MethodHandles.lookup();

MethodHandle handle = lookup.findStatic(Integer.class, "valueOf", methodType);

Function f=(Function)

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 f=(Function)

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值