JAVA8学习——深入浅出方法引用(学习过程)
方法引用:method reference
先简单的看一下哪里用到了方法引用:
public class MethodReferenceTest {
public static void main(String[] args) {
List<String> list = Arrays.asList("hello", "world", "hello world");
// list.forEach(item -> System.out.println(item));
list.forEach(System.out::println);
}
}
方法引用实际上是lambda表达式的一种语法糖
我们可以将方法引用看做一个「函数指针」,function pointer
方法引用共分为4类:
下面会逐步介绍四种类型,并且用代码实现:公用的Student类如下
package com.dawa.jdk8.methodreference;
public class Student {
private String name;
private int score;
public Student(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
//这两个方法,只是测试时候使用。实际设计有问题
public static int compareStudenyByScore(Student student, Student student2) {
return student.getScore() - student2.getScore();
}
public static int compareStudenyByName(Student student, Student student2) {
return student.getName().compareToIgnoreCase(student2.getName());
}
//这样设计才比较合理。
public int compareByScore(Student student) {
return this.score - student.getScore();
}
public int compareByName(Student student) {
return this.name.compareToIgnoreCase(student.getName());
}
}
1. 类名::方法名.
- 具体实现:
public class MethodReferenceTest {
public static void main(String[] args) {
Student student1 = new Student("dawa", 20);
Student student2 = new Student("erwa", 80);
Student student3 = new Student("sanwa", 60);
Student student4 = new Student("siwa", 40);
List<Student> list = Arrays.asList(student1, student2, student3, student4);
// list.sort((studentParam1, studentParam2) -> Student.compareStudenyByScore(studentParam1, studentParam2));
list.sort(Student::compareStudenyByScore);
list.forEach(item-> System.out.println(item.getScore()));
// list.sort((studentParam1, studentParam2) -> Student.compareStudenyByName(studentParam1, studentParam2));
list.sort(Student::compareStudenyByName);
list.forEach(item-> System.out.println(item.getName()));
}
}
2. 引用名(对象)::实例方法名
和第一种方法类似
定义一个实例:
package com.dawa.jdk8.methodreference;
public class StudentComparator {
public int compareStudentByScore(Student student1, Student student2) {
return student1.getScore() - student2.getScore();
}
public int compareStudentByName(Student student1, Student student2) {
return student1.getName().compareToIgnoreCase(student2.getName());
}
}
具体实现:
StudentComparator studentComparator = new StudentComparator();
//list.sort((studentParam1,studentParam2) ->studentComparator.compareStudentByName(studentParam1,studentParam2));
list.sort(studentComparator::compareStudentByScore);
list.sort(studentComparator::compareStudentByName);
3.类名::实例方法名
list.sort(Student::compareByScore);
list.sort(Student::compareByName);
//方法是谁来调用的?
//一定是 sort方法里面的lambda表达式的第一个参数来调用的compareByScore 实例方法
//而lambda表达式的后续参数,都将作为这个实例方法的参数
//扩展
List<String> cities = Arrays.asList("chengdu", "beijing", "shanghai", "chongqing");
//Collections.sort(cities,(value1,value2)->value1.compareToIgnoreCase(value2));
cities.sort(String::compareToIgnoreCase);
cities.forEach(System.out::println);
- 额外知识点扩展:
System.out这个类中的out参数是null;赋值是通过最上面的函数registerNatives():底层是通过C来通过底层GNI实现的。
因为输入输出设备本身是跟硬件相关的。所以用通过底层的C来完成的。
Out,In,err 等几个参数都是如此。
public final class System {
/* register the natives via the static initializer.
*
* VM will invoke the initializeSystemClass method to complete
* the initialization for this class separated from clinit.
* Note that to use properties set by the VM, see the constraints
* described in the initializeSystemClass method.
*/
private static native void registerNatives();
static {
registerNatives();
}
...
4. 构造方法引用:类名::new
实际上就够调用了构造方法来生成一个new对象。
public String getStr(Supplier<String> supplier) {
return supplier.get() + "test";
}
public String getString(String str, Function<String, String> function) {
return function.apply(str);
}
//在main方法中调用
MethodReferenceTest methodReferenceTest = new MethodReferenceTest();
methodReferenceTest.getStr(String::new);
methodReferenceTest.getString("hello", String::new);
默认方法
用案例再次解释默认方法
如果有两个接口,分别的默认方法签名都相同,都被一个类继承
类里面需要使用 Interface.super.method()来声明你要使用哪个方法。不然会编译器报错。
public interface MyInterface1 {
default void mymethod1(){
System.out.println("mymethod1");
}
}
public interface MyInterface2 {
default void mymethod1(){
System.out.println("mymethod2");
}
}
//如下
public class MyClass implements MyInterface1,MyInterface2 {
@Override
public void mymethod1() {
MyInterface2.super.mymethod1();
}
public static void main(String[] args) {
MyClass myClass = new MyClass();
myClass.mymethod1();
}
}
另外:如果一个类,继承了接口1的实现类,又实现了接口2
那么:默认调用实现类里面的方法。这是没有错的
因为:JAVA认为实现类更为具体,接口只是类的契约。默认
所以:类中调用的是接口1中的方法
回顾
- 方法引用的四种方式
- 类名::静态方法名
- 引用名::实例方法名
- 类名::实例方法名(特殊)
- 构造方法:类名::new
- 什么情况下会实现方法引用:
- lambda表达式只有一行方法
- 恰好这个方法和类中的方法对应
除此之外,方法引用是不能使用的。
方法引引用只是lambda的很具体的一种表达方式。
抛出一个问题:
JDK 为什么会有默认方法存在?是为了规避什么问题?
原因: 版本升级,引入默认方法,就是为了保证向后兼容。为了防止版本升级在接口中添加方法,对以前开发的项目实现破坏性的影响。
如List接口中的sort()方法。
JAVA8学习——深入浅出方法引用(学习过程)的更多相关文章
- java8学习之方法引用详解及默认方法分析
方法引用: 之前花了很多时间对Lambda表达式进行了深入的学习,接下来开启新的主题---方法引用(Method References),其实在之前的学习中已经使用过了,如: 那方法引用跟Lambda ...
- JAVA8学习——深入浅出Lambda表达式(学习过程)
JAVA8学习--深入浅出Lambda表达式(学习过程) lambda表达式: 我们为什么要用lambda表达式 在JAVA中,我们无法将函数作为参数传递给一个方法,也无法声明返回一个函数的方法. 在 ...
- java8新特性——方法引用与构造器引用
上篇文章简单学习了java8内置得4大核心函数式接口,这类接口可以解决我们遇到得大多数得业务场景得问题.今天来简单学习一下方法引用与构造器引用. 一.方法引用 方法引用:若lambda 体中得内容已经 ...
- JAVA8新特性——方法引用
JAVA9都要出来了,JAVA8新特性都没搞清楚,是不是有点掉队哦~ 在Lamda新特性的支持下,JAVA8中可以使用lamda表达式来创建匿名方法.然而,有时候我们仅仅是需要调用一个已存在的方法(如 ...
- Java8 新特性 方法引用
什么是方法引用 方法引用可以被看作仅仅调用特定方法的Lamdba表达式的一种快捷方式.比如说Lamdba代表的只是直接调用这个方法,最好还是用名称来调用它,可不用用对象.方法名(),方法引用,引用 ...
- Java8中的[方法引用]“双冒号”——走进Java Lambda(四)
前面的章节我们提及到过双冒号运算符,双冒号运算就是Java中的[方法引用],[方法引用]的格式是 类名::方法名 注意是方法名哦,后面没有括号“()”哒.为啥不要括号,因为这样的是式子并不代表一定会调 ...
- Java学习笔记-方法引用
方法引用(Method Reference) 上一篇中记录了Lambda表达式,其可以创建匿名方法.当Lambda表达式只是调用一个存在的方法时,可以采用方法引用(JDK8具有的特性).如下: pub ...
- java8新特性-方法引用
方法引用:若 Lambda 体中的功能,已经有方法提供了实现,可以使用方法引用 (可以将方法引用理解为 Lambda 表达式的另外一种表现形式) 1. 对象的引用 :: 实例方法名2. 类名 :: 静 ...
- Java8新特性 - 方法引用与构造器引用
方法引用 若Lambda体中的内容有方法已经实现了,我们可以使用"方法应用",可以理解为方法引用是Lambda表达式的另外一种表现形式. 使用操作符"::"将方 ...
随机推荐
- Python入门(上)
Python入门(上) Python入门(上) 简介 Python 基础语法 行与缩进 注释 运算符 标准数据类型 变量 编程流程 顺序(略) 分支 if 循环 for while break 和 c ...
- 安霸pipeline简述之YUV域的处理
YUV域处理模块的详细介绍: YUV域的处理主要是rgb_to_yuv_matrix,chroma_scale,ASF(空域降噪),MCTF(时域降噪),SharpenB(锐化模块). RGB2YUV ...
- 深入理解MySQL索引底层数据结构
作者:IT王小二 博客:https://itwxe.com MySQL 索引相关的数据结构有两种,一种是 B+tree,一种是 Hash,那么为什么在 99.99% 的情况下都使用的是 B+tree索 ...
- ctfshow web2 web3
ctfshow web2 1.手动注入题.先用万能密码admin' or 1=1%23,有回显 2.union select注入,2处有回显 3.依次查找数据库.表.字段 得到flag ctfshow ...
- Choregraphe 2.8.6.23动作失效
动作和动画执行完以后,无法自动还原成默认状态,自然接下来动作无法执行了.之后各种操作可能诱发软件原有的bug.需要开关自主生活模块才能恢复. 部分连贯的动作不需要恢复就能执行,动画不行. 站立动作好像 ...
- Cesium中级教程1 - 空间数据可视化(一)
Cesium中文网:http://cesiumcn.org/ | 国内快速访问:http://cesium.coinidea.com/ 本教程将教读者如何使用Cesium的实体(Entity)API绘 ...
- Cesium入门10 - 3D Tiles
Cesium入门10 - 3D Tiles Cesium中文网:http://cesiumcn.org/ | 国内快速访问:http://cesium.coinidea.com/ 我们团队有时把Ces ...
- Docker 实操
---恢复内容开始--- 一.简介 Linux容器作为一类操作系统层面的虚拟化技术成果,旨在立足于单一Linux主机交付多套隔离性Linux环境.与虚拟机不同,容器系统并不需要运行特定的访客操作系统. ...
- webStorm关于ESlint6语法格式化解决方案
方式1: 下载ESLint6 格式化插件(格式化蛋痛,有点卡,而且必须先保存) 方式2:更改快捷键 在设置中,将下面这个格式化选项设置快捷键即可 到设置中的下面这个选项找修改即可
- Understanding C++ Modules In C++20 (1)
Compiling evironment: linux (ubuntu 16.04)+ gcc-10.2. The Post will clarify and discuss what modules ...