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

不念不忘少年蓝@ 2023-03-02 10:16 50阅读 0赞

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

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

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

测试代码:

  1. package newjdk;
  2. public class Test04 {
  3. public static void main(String[] args) {
  4. // 引用静态方法
  5. Inter1<Integer, String> inter1 = String :: valueOf;
  6. String str1 = inter1.m1(100);
  7. System.out.println(str1); // 100
  8. // 引用某个对象的普通方法
  9. Inter2<String> inter2 = "HELLO" :: toLowerCase;
  10. String str2 = inter2.m2();
  11. System.out.println(str2); // hello
  12. // 引用特定类型的方法
  13. Inter3<String> inter3 = String :: compareTo;
  14. int res = inter3.m3("aa", "bb");
  15. System.out.println(res); // -1
  16. // 引用构造方法
  17. Inter4<Book> inter4 = Book :: new;
  18. Book b = inter4.m4("java编程入门", 25.36);
  19. System.out.println(b); // Book{name='java编程入门', price=25.36}
  20. }
  21. }
  22. interface Inter1<T, E> {
  23. public E m1(T t);
  24. }
  25. interface Inter2<T> {
  26. public T m2();
  27. }
  28. interface Inter3<T> {
  29. public int m3(T t1, T t2);
  30. }
  31. interface Inter4<T> {
  32. public T m4(String s, double d);
  33. }
  34. class Book {
  35. String name;
  36. double price;
  37. public Book() {
  38. }
  39. public Book(String name, double price) {
  40. this.name = name;
  41. this.price = price;
  42. }
  43. @Override
  44. public String toString() {
  45. return "Book{" + "name='" + name + '\'' +
  46. ", price=" + price + '}';
  47. }
  48. }

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

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

1、功能性接口(Function):

  1. public interface Function<T, R> {
  2. public R apply(T t);
  3. }

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


2、消费型接口(Consumer):

  1. public interface Consumer<T> {
  2. public void accept(T t);
  3. }

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


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


4、断言型接口(Predicate):

  1. public interface Predicate<T> {
  2. public boolean test(T t);
  3. }

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

发表评论

表情:
评论列表 (有 0 条评论,50人围观)

还没有评论,来说两句吧...

相关阅读

    相关 JAVA8特性--方法引用

    方法引用是什么? w3c教程上这样解释:方法引用通过方法的名字来指向一个方法。反正这句话我是看不明白啥意思,结合下面的要介绍的例子我认为这样解释更通俗易懂(了解方法引用前,