java中的方法参考 [英] Method reference in java

查看:114
本文介绍了java中的方法参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在探索java中的方法引用,并且好奇是否可以将以下内容转换为方法引用

I'm exploring method reference in java, and just curious if following can be converted to a method reference

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
list.forEach(item -> new SomeClass(item).someMethod(item));

我尝试了以下操作,但这不起作用

I tried the following, but that didn't work

list.forEach(SomeClass::new::someMethod);


推荐答案

无法解决问题的方法你提供。但是可以通过将 someMethod 方法定义为 static 来完成:

There is no way to resolve the issue in the way you provided. But it could be done by defining the someMethod method as static:

list.forEach(item -> SomeClass.someMethod(item));
list.forEach(SomeClass::someMethod);

语句 SomeClass :: new :: someMethod 不正确。
严格来说, SomeClass :: new 是指一段构造函数代码(如 Consumer ),当你需要一个对象来进行方法引用时,它不会返回一个新实例 SomeClassinstance :: someMethod

The statement SomeClass::new::someMethod is incorrect. Strictly speaking, SomeClass::new refers to a piece of constructor code (like a Consumer), it does not return a new instance while you need an object to make a method reference SomeClassinstance::someMethod.

编辑:

我真的没有看到这种方法的任何优点:


I really don't see any advantages of the approach:

map(SomeClass::new).forEach(SomeClass::someMet‌hod)

因为它会导致创建一部分无用的 SomeClass 具有 item 的实例也将不会被使用。

because it leads to creation a portion of useless SomeClass instances with items that also will not be used.

这篇关于java中的方法参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆