方法的引用
1. 静态方法引用 类名::staticMethod
2. 实例方法引用 inst::instMethod
3. 构建方法引用 类名::new
新建 Person.class
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@Data
@Slf4j
@NoArgsConstructor
@AllArgsConstructor
public class Person {
private String name;
private Integer age;
public static String testPerson(){
String text = "测试在 lambda 中方法的引用";
// log.info(text);
return text;
}
public static String testPerson02(String first){
String text = "测试在 lambda 中方法的引用,first:" + first ;
// log.info(text);
return text;
}
public static String testPerson03(String first, String second){
String text = "测试在 lambda 中方法的引用,first:" + first + " second:" + second;
return text;
}
public static String testPerson04(String first, String second, String three){
String text = "测试在 lambda 中方法的引用,first:" + first + " second:" + second + " three:" + three;
return text;
}
/**
* 无参的实例方法
* @return
*/
public String testExample(){
String text = "测试实例方法 ";
return text;
}
/**
* 带一个参的实例方法
* @return
*/
public String testExample02(String first){
String text = "测试实例方法 " + first;
return text;
}
/**
* 带两个参的实例方法
* @return
*/
public String testExample03(String first, String second){
String text = "测试实例方法 " + first + " second:" + second;
return text;
}
}
新建 MethodReference.class
import lombok.extern.slf4j.Slf4j;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;
/**
* 方法的引用
* 静态方法引用 类名::staticMethod
* 实例方法引用 inst::instMethod
* 构建方法引用 类名::new
* 在lambda里面使用
*/
@Slf4j
public class MethodReference {
public static void main(String[] args) {
// MethodReference.test01();
// MethodReference.test02();
MethodReference.test03();
}
/**
* 静态方法引用 类名::staticMethod
*/
public static void test01(){
Supplier<String> supplier = Person::testPerson;
String str = supplier.get();
log.info("调用一个无参的静态方法的引用:" + str);
Function<String, String> fn1 = Person::testPerson02;
String apply = fn1.apply("01");
log.info("调用一个参数的静态方法的引用:" + apply);
BiFunction<String, String, String> testPerson03 = Person::testPerson03;
String apply1 = testPerson03.apply("01", "02");
log.info("调用两个参数的静态方法的引用:" + apply1);
}
/**
* 实例方法引用
*/
public static void test02(){
Person person = new Person();
Supplier<String> testExample = person::testExample;
String noParam = testExample.get();
log.info("调用一个无参的实例方法:" + noParam);
Function<String, String> function01 = person::testExample02;
String apply01 = function01.apply("01");
log.info("调用带一个参数的实例方法:" + apply01);
BiFunction<String, String, String> biFunction = person::testExample03;
String apply02 = biFunction.apply("01", "02");
log.info("调用带两个参数的实例方法:" + apply02 );
}
/**
* 构建方法引用
*/
public static void test03(){
Supplier<Person> person = Person::new;
Person person1 = person.get();
log.info("构建方法引用:" + person1);
}
}