JDK8_方法引用
Lambad 表达式是基础,我们在熟悉 Lambad 后,可以直接通过方法应用来简写 Lambad 表达式中已经存在的方法。
- 方法引用通过方法的名字来指向一个方法
- 方法应用可以使用代码变得简洁优雅,减少冗余代码
- 方法的引用使用一对冒号 ::
代码例子 - 1:
package com.example.demo.methodreference;
import java.util.Arrays;
import java.util.List;
/**
* @author LaIWeiChun
*/
public class Study {
@FunctionalInterface
public interface Supplier<T> {
T get();
}
//Supplier是jdk1.8的接口,这里和Lamda一起使用了
/**
* @param supplier jdk函数时接口-无参数返回一个结果
* @return
*/
public static Study create(final Supplier<Study> supplier) {
return supplier.get();
}
public static void morning(final Study study) {
System.out.println("Morning study:" + study.toString());
}
public void afternoon(final Study study) {
System.out.println("Afternoon study: " + study.toString());
}
public void night() {
System.out.println("Night study:" + this.toString());
}
public static void main(String[] args) {
/**
* 构造器引用
* 语法:Class::new
*/
Study study = Study.create(Study::new);
List<Study> studys = Arrays.asList(study);
/**
* 静态方法引用
* 语法: Class::static_method
*/
studys.forEach(Study::morning);
/**
* 特定类的任意对象的方法引用
* 语法:Class::method
*/
studys.forEach(Study::night);
/**
* 特定对象的方法引用
* 语法:instance::method
*/
final Study study1 = Study.create(Study::new);
studys.forEach(study1::afternoon);
}
}
代码例子 - 2:
package com.example.demo.methodreference;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
/**
* @author LaIWeiChun
*/
public class Game {
public Game() {
}
public Game(String gameName) {
}
private static void game(String gameName) {
System.out.println(gameName + "- 始终受人喜欢");
}
/**
* Java里面默认把当前入参 Game this
* @param gameName
* @return
*/
private String gameToName(Game this,String gameName) {
return "我喜欢的人是 - " + gameName;
}
public static void main(String[] args) {
/**
* 方法应用
* 语法:Class::method
*/
Consumer<String> consumer = System.out::println;
consumer.accept("这是一个普通的方法引用");
/**
* 静态方法应用
* 语法:Class::static_method
*/
Consumer<String> consumer2 = Game::game;
consumer2.accept("LOL");
/**
* 特定类的任意对象的方法引用
* 语法:Class::method
*/
Game game = new Game();
Function<String, String> gameToName = game::gameToName;
System.out.println(gameToName.apply("恩静"));
/**
* 构造函数应用
* 语法:Class::new
*/
Supplier<Game> supplier = Game::new;
Game gameExample = supplier.get();
/**
* 构造函数应用 - 带参数
* 语法:Class::new
*/
Function<String,Game> function = Game::new;
function.apply("LoL");
}
}
总结:
- 构造器引用
- 静态方法引用
- 特定类的任意对象的方法引用
- 特定对象的方法引用
注:本文章只为学习记录