方法引用

需要合适的函数接口来接收。函数接口中的抽象函数参数列表与返回值,,要与方法或静态方法的 参数列表和返回值相对应。

  1. 静态方法的引用、

Lambda参数是示例方法的参数,则可以使用

  1. package cn.unuuc.java.methed;
  2. @FunctionalInterface
  3. interface Converter<F,T>{
  4. T convert(F from);
  5. }
  6. public class Test {
  7. public static void main(String[] args) {
  8. // 使用Lambda
  9. Converter<String,Integer> converter1 = (from -> Integer.valueOf(from));
  10. // 静态方法引用,valueOf为静态方法
  11. Converter<String,Integer> converter2 = Integer::valueOf;
  12. }
  13. }

上面的示例中演示了静态方法的引用,通过 :: 的形式,将静态方法替代了Lambda中的方法体部分。

  1. 对象方法的引用

对象方法的引用,一定是存在对象的情况下,对对象进行引用,没有对象则无法引用。

  1. package cn.unuuc.java.methed;
  2. import cn.unuuc.java.MyFunctionalInterface;
  3. import java.util.function.Function;
  4. class Demo{
  5. public String hello(){
  6. return "hello";
  7. }
  8. public static String world(String s){
  9. return "world";
  10. }
  11. }
  12. public class Test {
  13. public static void main(String[] args) {
  14. Demo demo = new Demo();
  15. // MyFunctionalInterface是自定义的函数接口
  16. MyFunctionalInterface hello = demo::hello;
  17. // 静态方法需要传参,需要使用函数接口类型来接受
  18. Function<String, String> world = Demo::world;
  19. }
  20. }
  1. 第三种情况

函数接口中抽象方法,在使用Lambda时候,第一个参数是实例方法的调用者,第二个参数是实例方法的参数,那么可以使用方法引用。

  1. @Test
  2. public void test09(){
  3. BiPredicate<String,String> bp1 = (x,y)-> x.equals(y);
  4. BiPredicate<String,String> bp2 = String::equals;
  5. }

构造函数引用

格式:
ClassName::new
**

  1. package cn.unuuc.java8;
  2. public class Person {
  3. private Integer id;
  4. private String name;
  5. private Integer age;
  6. public Person() {
  7. }
  8. public Person(Integer id) {
  9. this.id = id;
  10. }
  11. public Person(String name, Integer age) {
  12. this.name = name;
  13. this.age = age;
  14. }
  15. public Person(Integer id, String name, Integer age) {
  16. this.id = id;
  17. this.name = name;
  18. this.age = age;
  19. }
  20. }

测试方法中,将通过构造器引用来实现对象的创建

  1. // 无参数构造函数引用
  2. @Test
  3. public void test01(){
  4. // Lambda表达式
  5. Supplier<Person> sup = ()-> new Person();
  6. // 构造器引用
  7. Supplier<Person> sup2 = Person::new;
  8. Person person = sup2.get();
  9. }
  1. // 1个参数构造函数引用
  2. @Test
  3. public void test02(){
  4. // Lambda
  5. Function<Integer,Person> fun = (x)-> new Person(x);
  6. // 构造器引用
  7. Function<Integer,Person> fun2 = Person::new;
  8. Person apply = fun2.apply(1);
  9. }
  1. // 2个参数构造函数引用
  2. @Test
  3. public void test03(){
  4. // Lambda
  5. BiFunction<String,Integer,Person> biFun = (x,y)->new Person(x,y);
  6. // 构造器引用
  7. BiFunction<String,Integer,Person> biFun2 = Person::new;
  8. Person chen = biFun2.apply("chen", 22);
  9. }

总结:
构造器的引用要与函数接口中抽象方法参数列表要一致,这里的函数结构是可以自己定义的,不一定非要使用jdk自带的函数接口。
**
对于数组也是可以进行引用的

  1. @Test
  2. public void test04(){
  3. // Lambda
  4. Function<Integer,String[]> fun = (x)->new String[x];
  5. // 构造器引用
  6. Function<Integer,String[]> fun2 = String[]::new;
  7. String[] strs = fun2.apply(20);
  8. }