Bootstrap

Java | 方法引用符

方法引用符——双冒号 ::

其所在的表达式称为方法引用,方法引用是Lambda的孪生兄弟

一、常见的引用方法

1、引用类方法(类的静态方法)

类名::静态方法

public class ConverterDemo {
    public static void main(String[] args) {
        //Lambda
        useConverter(s -> Integer.parseInt(s));
        //方法引用
        useConverter(Integer::parseInt);
    }

    private static void useConverter(Converter c){
        int num = c.convert("55");
        System.out.println(num);
    }
}


interface Converter {
    int convert(String s);
}

Lambda表达式被类方法替代的时候,他的形式参数全部传递给该方法作为参数。

2、引用对象的实例方法

对象::成员方法

public class PrinterDemo {
    public static void main(String[] args) {
        //Lambda
        usePrinter(s -> System.out.println(s.toUpperCase()));

        //方法引用
        PrintString ps = new PrintString();
        usePrinter(ps::printUpper);
    }

    private static void usePrinter(Printer p){
        p.toUpper("hello world");
    }
}



interface Printer {
    void toUpper(String s);
}



class PrintString {
    public void printUpper(String s){
        String s1 = s.toUpperCase();
        System.out.println(s1);
    }
}

Lambda表达式被对象的实例方法替代的时候,他的形式参数全部传递给该方法作为参数。

3、引用类的实例方法

类名::成员方法

public class MyStringDemo {
    public static void main(String[] args) {
        //Lambda
        useMystring((s, x, y)->{
            return s.substring(x,y);
        });

        //方法引用
        useMystring(String::substring);
    }

    private static void useMystring(MyString my){
        String s = my.mySubstring("HelloWorld", 2, 6);
        System.out.println(s);
    }
}


interface MyString {
    String mySubstring(String s, int x, int y);
}

Lambda表达式被类的实例方法替代的时候,第一个参数作为调用者,后面的参数全部传递给该方法作为参数。

4、引用构造器(构造方法)

类名::new

public class StudentDemo {
    public static void main(String[] args) {
        //Lambda
        useStudent((name,age)-> new Student(name, age));

        //方法引用
        useStudent(Student::new);
    }

    private static void useStudent(StudentBuilder sb) {
        Student s = sb.build("Anna", 10);
        System.out.println(s.getName() + ":" + s.getAge());
    }
}


interface StudentBuilder {
    Student build(String name, int age);
}



class Student {
    private String name;
    private int age;

    public Student() {
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

Lambda表达式被构造器替代时,他的形式参数全部传递给构造器作为参数

;