1. 程式人生 > >JDK8新特性,方法的引用

JDK8新特性,方法的引用

技術分享 main 圖片 new cto ger ons alt 標識

引用方法並運行

在Java中,方法和構造方法都看作是對象的一種,那麽你要引用它(不是調用),則可以用::來引用。用來存儲這個引用的類型用@FunctionlaInterface註解來標識。

示例:

package fun;

/**
 * @author 施俊傑
 * @email [email protected]
 */
public class TestMethods {
    
    @FunctionalInterface
     interface Fun<F1, F2, T> {
         T myrun(F1 from1, F2 from2);
     }
    
     
public int add(int x, int y) { return x+y; } public static void main(String[] args) { Fun<Integer, Integer, Integer> f = new TestMethods()::add; int i = f.myrun(1, 2); System.out.println(i); System.out.println(f.toString()); } }

運行結果:

技術分享圖片

通過引用構造函數來創建對象

示例如下

package interfacetest;

/**
 * @author 施俊傑
 * @email [email protected]
 */
public class TestMethods2 {
    private int i;
    private int j;
    public TestMethods2(int i, int j) {
        this.i = i;
        this.j = j;
    }
    public int getI() {
        return i;
    }
    
public void setI(int i) { this.i = i; } public int getJ() { return j; } public void setJ(int j) { this.j = j; } @Override public String toString() { return "TestMethods2 [i=" + i + ", j=" + j + "]"; } @FunctionalInterface interface constructor<F1, F2, T> { T create(F1 f1, F2 f2); } public static void main(String[] args) { constructor<Integer, Integer, TestMethods2> c = TestMethods2::new; TestMethods2 obj = c.create(1, 2); System.out.println(obj); } }

運行結果:

技術分享圖片

JDK8新特性,方法的引用