JDK8新特性,方法引用的4种形式

JDK8新特性,方法引用的4种形式:

前提条件是:定义的接口中只能有一个方法,才能实现方法的引用。

引用静态方法: 类名::静态方法名
引用某个对象的方法: 对象::实例方法
引用特定类型的方法: 特定类::实例方法
引用构造方法: 类名::new

测试代码:

package newjdk;

public class Test04 {
    public static void main(String[] args) {

        // 引用静态方法
        Inter1<Integer, String> inter1 = String :: valueOf;
        String str1 = inter1.m1(100);
        System.out.println(str1);  // 100

        // 引用某个对象的普通方法
        Inter2<String> inter2 = "HELLO" :: toLowerCase;
        String str2 = inter2.m2();
        System.out.println(str2);  // hello

        // 引用特定类型的方法
        Inter3<String> inter3 = String :: compareTo;
        int res = inter3.m3("aa", "bb");
        System.out.println(res);  // -1

        // 引用构造方法
        Inter4<Book> inter4 = Book :: new;
        Book b = inter4.m4("java编程入门", 25.36);
        System.out.println(b);  // Book{name='java编程入门', price=25.36}
    }
}

interface Inter1<T, E> {
    public E m1(T t);
}

interface Inter2<T> {
    public T m2();
}

interface Inter3<T> {
    public int m3(T t1, T t2);
}

interface Inter4<T> {
    public T m4(String s, double d);
}

class Book {
    String name;
    double price;

    public Book() {

    }
    public Book(String name, double price) {
        this.name = name;
        this.price = price;
    }

    @Override
    public String toString() {
        return "Book{" + "name='" + name + '\'' +
                ", price=" + price + '}';
    }
}

我们发现4种方法引用对应4种接口,并且每个接口中都只有一个方法。

那么在java.util.*中其实java已经为我们定义好了这4种接口。
它们分别是:

1、功能性接口(Function):

public interface Function<T, R> {
	public R apply(T t);
}

此接口需要接收一个参数,并且返回一个处理结果。


2、消费型接口(Consumer):

public interface Consumer<T> {
	public void accept(T t);
}

此接口只是负责接收数据,而且并不返回处理结果。


3、供给型接口(Supplier):
public interface Supplier {
public T get();
}
此接口不接收参数,但是返回一个处理结果。


4、断言型接口(Predicate):

public interface Predicate<T> {
	public boolean test(T t);
}

此接口接收一个参数,进行判断后返回结果。

猜你喜欢

转载自blog.csdn.net/pipizhen_/article/details/107640953
今日推荐