java – 将MethodHandle转换为方法引用(此处为Function)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – 将MethodHandle转换为方法引用(此处为Function),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2432字,纯文字阅读大概需要4分钟。
内容图文
![java – 将MethodHandle转换为方法引用(此处为Function)](/upload/InfoBanner/zyjiaocheng/700/9e8fdc0850ff4963855c4b5192e094a4.jpg)
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 documentation和it’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 – 将MethodHandle转换为方法引用(此处为Function)全部内容,希望文章能够帮你解决java – 将MethodHandle转换为方法引用(此处为Function)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。