4-6 Java新特性玩转JDK8之方法与构造函数引用
如果您还没有阅读本章须知,请先阅读➡ 本章须知
视频课程代码:
User用户类
public class User {
private String name;
private int age;
public User() {
}
public User(String name, int age) {
this.name = name;
this.age = age;
}
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
主方法
public class Main {
public static void main(String[] args) {
// 使用双冒号 :: 来构造静态函数的引用
// Integer.parseInt("wew")
Function<String,Integer> fun = Integer::parseInt;
Integer value = fun.apply("1024");
System.out.println(value);
// 使用双冒号 :: 来构造非静态函数的引用
String content = "欢迎来到小滴课堂学习";
Function<Integer,String> func = content::substring;
String result = func.apply(1);
System.out.println(result);
// 使用双冒号 :: 来引用构造方法
BiFunction<String,Integer,User> biFunction = User::new;
User user = biFunction.apply("小滴课堂", 2);
System.out.println(user);
sayHello(String::toUpperCase, "xdclass.net");
}
private static void sayHello(Function<String,String> fun,String param){
String result = fun.apply(param);
System.out.println(result);
}
}
分类详解:
使用双冒号 :: 来构造静态函数的引用
- 格式:类名 : : 方法名
引用Integer.parseInt(String s)方法 字符串转int类型
public class Main {
public static void main(String[] args) {
// 使用双冒号 :: 来构造静态函数的引用
Function<String,Integer> function = Integer::parseInt;
Integer integer = function.apply("12345");
System.out.println(integer+1);
// 打印结果12346
}
}
使用双冒号 :: 来构造非静态函数的引用
- 格式:对象名 : : 方法名
引用String对象的substring(int n) 方法截取字符串
public class Main {
public static void main(String[] args) {
// 使用双冒号 :: 来构造非静态函数的引用
String content = "欢迎来到小滴课堂学习";
Function<Integer,String> func = content::substring;
String result = func.apply(1);
System.out.println(result);
// 输出打印 迎来到小滴课堂学习
}
}
使用双冒号 :: 来引用构造函数
- 格式:类名 : : new
User类在上方有说明。引用User类构造函数。
public class Main {
public static void main(String[] args) {
BiFunction<String,Integer,User> biFunction = User::new;
User user = biFunction.apply("小滴课堂", 2);
System.out.println(user);
}
}
原文地址: https://www.yuque.com/books/share/94d7e9ce-40a5-4878-97f2-c6297f679886