为什么JAVA可以通过 “类::实例方法” 的方式获取到方法的引用?
对于JAVA的方法引用“类::实例方法”的方式的疑惑
/*
1. 被引用方法的参数,需要与抽象方法的第2个到最后1个参数保持一致
ps: 实例方法的第1个参数其实是隐含的this
如果这个this (实例对象) 的类型与抽象方法的第一个参数类型一致,就可以用类名引用实例方法
*/
ArrayList<String> list = new ArrayList<>();
Collections.addAll(list, "a", "b", "c");
// 将集合中的字母转为大写
list.stream()
// 数据流中的数据类型为 String,所以可以引用 String 类中的实例方法
.map(String::toUpperCase)
.forEach(System.out::println);
请问按照注释中的理解,是否是正确的呢?
回复
1个回答

test
2024-06-19
这个是 Method Reference Expression。
此时,如果它是类成员函数,调用的第一个参数就是调用函数的对象,后续参数是调用成员函数的参数。
基本跟你注释里写的差不多。
If the form is ReferenceType :: [TypeArguments] Identifier, the body of the invocation method similarly has the effect of a method invocation expression for a compile-time declaration which is the compile-time declaration of the method reference expression. Run-time evaluation of the method invocation expression is as specified in §15.12.4.3, §15.12.4.4, and §15.12.4.5, where:
- The invocation mode is derived from the compile-time declaration as specified in §15.12.3.
- If the compile-time declaration is an instance method, then the target reference is the first formal parameter of the invocation method. Otherwise, there is no target reference.
- If the compile-time declaration is an instance method, then the arguments to the method invocation expression (if any) are the second and subsequent formal parameters of the invocation method. Otherwise, the arguments to the method invocation expression are the formal parameters of the invocation method.
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容