簡體   English   中英

在Java 8中使用功能接口

[英]Use of Functional Interface in Java 8

這是Java 8::(雙冒號)運算符的后續問題,其中Java允許您使用::運算符引用方法。

是否可以提供我創建的一些自定義功能接口並將其與::運算符一起使用? 怎么做?

“是否有可能提供我創建的一些自定義功能接口並將其與::運算符一起使用? 怎么做?“

這是可能的,它就像你想象的那樣簡單:只需用一種方法創建一個界面。 你甚至不需要@FunctionalInterface注釋; 這個注釋只記錄了你的意圖,並有助於在編譯時檢測錯誤,類似於@Override

所以也許你已經在Java 8之前的項目中創建了這樣的接口......

class Foo {
    // nothing new:
    public interface FooFactory {
        Foo createFoo();
    }
    // new in Java 8:
    public static final FooFactory DEFAULT_FACTORY = Foo::new;
}

如何使用:: operator提供自定義功能接口實現

public class TestingLambda {

    public static void main(String[] args) {
        int value1 = method(TestingLambda::customMethod1);
        int value2 = method(TestingLambda::customMethod2);

        System.out.println("Value from customMethod1: " + value1);
        System.out.println("Value from customMethod2: " + value2);
    } 

    public static int customMethod1(int arg){
        return arg + 1;
    }

    public static int customMethod2(int arg){
        return arg + 2;
    }

    public static int method(MyCustomInterface ob){
        return ob.apply(1);
    }

    @FunctionalInterface
    interface MyCustomInterface{
        int apply(int arg);
    }
}

階段1:創建自定義功能界面

我創建了自己的名為MyCustomInterfaceFunctionalInterface ,在Java 8中,您必須使用@FunctionalInterface注釋將接口聲明為功能接口。 現在它有一個方法,將int作為param並返回int

階段2:創建一些確認該簽名的方法

創建了兩個方法customMethod1customMethod2 ,它們確認該自定義接口的簽名。

階段3:創建一個以功能接口( MyCustomInterface )作為參數的方法

method在參數中使用MyCustomInterface

你准備好了。

階段4:使用

在主要方面,我使用了該method並將其傳遞給我自定義方法的實現。

method(TestingLambda::customMethod1); 

干得好

import java.util.Arrays;

class Sort {
    public int compareByLength(String s1, String s2) {
        return (s1.length() - s2.length());
    }
}

public class LambdaReferenceExample1 {
    public static void main(String[] javalatteLambda) {
        String[] str = {"one", "two", "3", "four", "five", "sixsix", 
            "sevennnnn", "eight"};
        Sort sort = new Sort();
        Arrays.sort(str, sort::compareByLength);

        for (String s : str) {
            System.out.println(s);
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM