Lambda表达式的方法引用和构造器引用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chengqiuming/article/details/91354594

一 点睛

如果Lambda表达式的代码块只有一条代码,还可以在代码块中使用方法引用和构造器引用,以使得Lambda表达式更加简洁。

种类

示例

说明

对应的Lambda表达式

引用类方法

类名::类方法

函数式接口中被实现方法的全部参数传给该类方法作为参数。

(a,b,...) -> 类名.类方法(a,b, ...)

引用特定对象的实例方法

特定对象::实例方法

函数式接口中被实现方法的全部参数传给该方法作为参数。

(a,b, ...) -> 特定对象.实例方法(a,b, ...)

引用某类对象的实例方法

类名::实例方法

函数式接口中被实现方法的第一个参数作为调用者,后面的参数全部传给该方法作为参数。

(a,b, ...) ->a.实例方法(b, ...)

引用构造器

类名::new

函数式接口中被实现方法的全部参数传给该构造器作为参数。

(a,b, ...) ->new 类名(a,b, ...)

二 实战

1 代码

import javax.swing.*;

@FunctionalInterface
interface Converter{
   Integer convert(String from);
}
@FunctionalInterface
interface MyTest
{
   String test(String a , int b , int c);
}
@FunctionalInterface
interface YourTest
{
   JFrame win(String title);
}
public class MethodRefer
{
   public static void main(String[] args)
   {
      // 下面代码使用Lambda表达式创建Converter对象
//    Converter converter1 = from -> Integer.valueOf(from);
      // 方法引用代替Lambda表达式:引用类方法。
      // 函数式接口中被实现方法的全部参数传给该类方法作为参数。
      Converter converter1 = Integer::valueOf;
      Integer val = converter1.convert("99");
      System.out.println(val); // 输出整数99



      // 下面代码使用Lambda表达式创建Converter对象
//    Converter converter2 = from -> "fkit.org".indexOf(from);
      // 方法引用代替Lambda表达式:引用特定对象的实例方法。
      // 函数式接口中被实现方法的全部参数传给该方法作为参数。
      Converter converter2 = "fkit.org"::indexOf;
      Integer value = converter2.convert("it");
      System.out.println(value); // 输出2



      // 下面代码使用Lambda表达式创建MyTest对象
//    MyTest mt = (a , b , c) -> a.substring(b , c);
      // 方法引用代替Lambda表达式:引用某类对象的实例方法。
      // 函数式接口中被实现方法的第一个参数作为调用者,
      // 后面的参数全部传给该方法作为参数。
      MyTest mt = String::substring;
      String str = mt.test("Java I Love you" , 2 , 9);
      System.out.println(str); // 输出:va I Lo



      // 下面代码使用Lambda表达式创建YourTest对象
//    YourTest yt = (String a) -> new JFrame(a);
      // 构造器引用代替Lambda表达式。
      // 函数式接口中被实现方法的全部参数传给该构造器作为参数。
      YourTest yt = JFrame::new;
      JFrame jf = yt.win("我的窗口");
      System.out.println(jf);
   }
}

2 运行

99
2
va I Lo
javax.swing.JFrame[frame0,0,0,0x0,invalid,hidden,layout=java.awt.BorderLayout,title=我的窗口,resizable,normal,defaultCloseOperation=HIDE_ON_CLOSE,rootPane=javax.swing.JRootPane[,0,0,0x0,invalid,layout=javax.swing.JRootPane$RootLayout,alignmentX=0.0,alignmentY=0.0,border=,flags=16777673,maximumSize=,minimumSize=,preferredSize=],rootPaneCheckingEnabled=true]

猜你喜欢

转载自blog.csdn.net/chengqiuming/article/details/91354594