符号说明:双冒号为方法引用运算符,而它所在的表达式被称为方法引用
应用场景:如果Lambda表达式所要实现的方案,已经有其他方法存在相同的方案,那么则可以使用方法引用。常见的引用方式:
方法引用在IDK8中使用是相当灵活的,有以下几种形式:
1、instanceName:methodName对象::方法名
2、ClassName:staticMethodName类名::静态方法
3、ClassName::methodName类名::普通方法
4、lassNamenew类名::new调用的构造器
5、ypeName[]:new String::new调用数组的构造器
案例中所用到的实体类位于文章最后方。
@Test
public void test1(){
Date date = new Date();
Supplier<Long> supplier1=()->date.getTime();
System.out.println(supplier1.get());
Supplier<Long> supplier2=date::getTime;
System.out.println(supplier2);
}
@Test
public void test2(){
User user = new User();
user.setUsername("茴子白苗");
Supplier supplier=user::getUsername;
System.out.println(supplier.get());
}
方法引用的注意事项:
1.被引用的方法,参数要和接口中的抽象方法的参数一样
2.当接口抽象方法有返回值时,被引用的方法也必须有返回值
@Test
public void test3(){
Supplier<Long> supplier1=()->System.currentTimeMillis();
System.out.println(supplier1.get());
Supplier<Long> supplier2=System::currentTimeMillis;
System.out.println(supplier2.get());
}
@Test
public void test4() {
Function<String, Integer> function1 = (s) -> s.length();
Function<String, Integer> function2 = String::length;
System.out.println(function1.apply("hello"));
System.out.println(function2.apply("hello"));
}
@Data
@AllArgsConstructor
class Person {
private Integer age;
private String name;
}
@Test
public void test5() {
/*以下可以进行无参构造*/
Supplier<User> supplier1 = () -> new User();
Supplier<User> supplier2 = User::new;
/*以下可以进行有参构造*/
//lambda表达式
BiFunction<Integer,String,Person> biFunction1=(a,b)->new Person(a,b);
Person person1 = biFunction1.apply(12, "茴子白苗");
System.out.println(person1.toString());
//方法引用
BiFunction<Integer,String,Person> biFunction2=Person::new;
Person person2 = biFunction2.apply(13, "西红柿苗");
System.out.println(person2);
}
@Test
public void test6() {
/*lambda表达式*/
Function<Integer,String[]> function1=(a)->new String[a];
System.out.println(function1.apply(5).length);
/*方法引用*/
Function<Integer,String[]> function2=String[]::new;
System.out.println(function2.apply(8).length);
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Long id;
private String username;
private String password;
private String phoneNum;
private String email;
private Role role;
}
进行练习时,添加Lombok插件,同时添加Lombok依赖。
org.projectlombok
lombok
1.18.20
junit
junit
4.13.2