Java 8方法引用使用指南

helloyou0 8年前發布 | 10K 次閱讀 Java8 Java開發

 

【編者按】本文作者為擁有15年Java 開發經驗的資深程序員 Per-?ke Minborg ,主要介紹如何靈活地解析 Java 中的方法引用。文章系國內ITOM 管理平臺OneAPM 編譯呈現。

方法引用

眾所周知,在Java 8中我們可以使用方法引用。譬如,在我們需要遍歷流元素時,可以使用 String::isEmpty 來引用 isEmpty 方法。試看下面這段代碼:

Stream.of("A", "", "B").filter(Stream::isEmpty).count();

運行的結果為1(因為在這個流中只有一個空元素)。但是,如果我們要過濾出非空字符串,我們得寫成 .filter(s -> !s.isEmpty()) 。這是一個Lambda表達式。顯然,這兒有個討厭的不對稱想象。我們可以使用方法引用,但卻不能用它的反式。我們可以寫 predicate.negate() 卻不能寫 Stream::isEmpty.negate() 或 !Stream::isEmpty 。

為什么呢?這是因為方法引用并非Lambda表達式或者函數接口。不過,使用Java的類型推導可以將方法引用解析為一個或多個函數接口。上例中的 String::isEmpty 至少可以解析為:

Predicate<String>
Function<String, Boolean>

所以,我們要排除其他可能性,確定到底將方法引用轉換為哪個函數接口。本文在一定程度上解決了該問題。文中的代碼來自開源項目 Speedment ,它讓數據庫看起來像Java 8的流。

解析方法引用

其實,以靜態方法為“管道”,可以部分地解決這個問題——該靜態方法以一個方法引用為輸入,以特定的函數接口為其返回。試考慮下面這個簡短的靜態方法:

public static <T> Predicate<T> as(Predicate<T> predicate) {
    return predicate;
}

現在,如果靜態地導入這個方法,事實上,我們就能更簡單地使用方法引用。如下例所示:

Stream.of("A", "", "B").filter(as(String::isEmpty).negate()).count();

這段代碼返回的結果為2,即流中非空元素的數量。有關方法引用的使用方式,我們又向前邁進了一步。另一個好處是,這個解決方案讓我們更輕松地編寫predicates接口,例如:

.filter(as(String::isEmpty).negate().and("A"::equals))

解析所有方法引用

但是,現在仍有一個問題亟待解決。我們不能隨隨便便地創建一大堆靜態 as() 函數,因為一個方法引用可能解析為多種 as() 方法,正如本文開頭提到的那樣。所以,一個更妙的解決方案,是把函數接口類型名添加至每個靜態方法,這樣我們就可以程序化地為每個函數接口轉換方法選擇一個特定的方法引用。我們有一個工具類,可以讓每個方法引用都轉換為Java標準包 `java.util.function中任意匹配的函數接口。

直接在 GitHub 下載最新版本

import java.util.function.*;
/**
 *
 * @author Per Minborg
 */
public class FunctionCastUtil {
    public static <T, U> BiConsumer<T, U> asBiConsumer(BiConsumer<T, U> biConsumer) {
        return biConsumer;
    }
    public static <T, U, R> BiFunction<T, U, R> asBiFunction(BiFunction<T, U, R> biFunction) {
        return biFunction;
    }
    public static <T> BinaryOperator<T> asBinaryOperator(BinaryOperator<T> binaryOperator) {
        return binaryOperator;
    }
    public static <T, U> BiPredicate<T, U> asBiPredicate(BiPredicate<T, U> biPredicate) {
        return biPredicate;
    }
    public static BooleanSupplier asBooleanSupplier(BooleanSupplier booleanSupplier) {
        return booleanSupplier;
    }
    public static <T> Consumer<T> asConsumer(Consumer<T> consumer) {
        return consumer;
    }
    public static DoubleBinaryOperator asDoubleBinaryOperator(DoubleBinaryOperator doubleBinaryOperator) {
        return doubleBinaryOperator;
    }
    public static DoubleConsumer asDoubleConsumer(DoubleConsumer doubleConsumer) {
        return doubleConsumer;
    }
    public static <R> DoubleFunction<R> asDoubleFunction(DoubleFunction<R> doubleFunction) {
        return doubleFunction;
    }
    public static DoublePredicate asDoublePredicate(DoublePredicate doublePredicate) {
        return doublePredicate;
    }
    public static DoubleToIntFunction asDoubleToIntFunction(DoubleToIntFunction doubleToIntFunctiontem) {
        return doubleToIntFunctiontem;
    }
    public static DoubleToLongFunction asDoubleToLongFunction(DoubleToLongFunction doubleToLongFunction) {
        return doubleToLongFunction;
    }
    public static DoubleUnaryOperator asDoubleUnaryOperator(DoubleUnaryOperator doubleUnaryOperator) {
        return doubleUnaryOperator;
    }
    public static <T, R> Function<T, R> asFunction(Function<T, R> function) {
        return function;
    }
    public static IntBinaryOperator asIntBinaryOperator(IntBinaryOperator intBinaryOperator) {
        return intBinaryOperator;
    }
    public static IntConsumer asIntConsumer(IntConsumer intConsumer) {
        return intConsumer;
    }
    public static <R> IntFunction<R> asIntFunction(IntFunction<R> intFunction) {
        return intFunction;
    }
    public static IntPredicate asIntPredicate(IntPredicate intPredicate) {
        return intPredicate;
    }
    public static IntSupplier asIntSupplier(IntSupplier intSupplier) {
        return intSupplier;
    }
    public static IntToDoubleFunction asIntToDoubleFunction(IntToDoubleFunction intToDoubleFunction) {
        return intToDoubleFunction;
    }
    public static IntToLongFunction asIntToLongFunction(IntToLongFunction intToLongFunction) {
        return intToLongFunction;
    }
    public static IntUnaryOperator asIntUnaryOperator(IntUnaryOperator intUnaryOperator) {
        return intUnaryOperator;
    }
    public static LongBinaryOperator asLongBinaryOperator(LongBinaryOperator longBinaryOperator) {
        return longBinaryOperator;
    }
    public static LongConsumer asLongConsumer(LongConsumer longConsumer) {
        return longConsumer;
    }
    public static <R> LongFunction<R> asLongFunction(LongFunction<R> longFunction) {
        return longFunction;
    }
    public static LongPredicate asLongPredicate(LongPredicate longPredicate) {
        return longPredicate;
    }
    public static <T> LongSupplier asLongSupplier(LongSupplier longSupplier) {
        return longSupplier;
    }
    public static LongToDoubleFunction asLongToDoubleFunction(LongToDoubleFunction longToDoubleFunction) {
        return longToDoubleFunction;
    }
    public static LongToIntFunction asLongToIntFunction(LongToIntFunction longToIntFunction) {
        return longToIntFunction;
    }
    public static LongUnaryOperator asLongUnaryOperator(LongUnaryOperator longUnaryOperator) {
        return longUnaryOperator;
    }
    public static <T> ObjDoubleConsumer<T> asObjDoubleConsumer(ObjDoubleConsumer<T> objDoubleConsumer) {
        return objDoubleConsumer;
    }
    public static <T> ObjIntConsumer<T> asObjIntConsumer(ObjIntConsumer<T> objIntConsumer) {
        return objIntConsumer;
    }
    public static <T> ObjLongConsumer<T> asObjLongConsumer(ObjLongConsumer<T> objLongConsumer) {
        return objLongConsumer;
    }
    public static <T> Predicate<T> asPredicate(Predicate<T> predicate) {
        return predicate;
    }
    public static <T> Supplier<T> asSupplier(Supplier<T> supplier) {
        return supplier;
    }
    public static <T, U> ToDoubleBiFunction<T, U> asToDoubleBiFunction(ToDoubleBiFunction<T, U> toDoubleBiFunction) {
        return toDoubleBiFunction;
    }
    public static <T> ToDoubleFunction<T> asToDoubleFunction(ToDoubleFunction<T> toDoubleFunction) {
        return toDoubleFunction;
    }
    public static <T, U> ToIntBiFunction<T, U> asToIntBiFunction(ToIntBiFunction<T, U> toIntBiFunction) {
        return toIntBiFunction;
    }
    public static <T> ToIntFunction<T> asToIntFunction(ToIntFunction<T> ioIntFunction) {
        return ioIntFunction;
    }
    public static <T, U> ToLongBiFunction<T, U> asToLongBiFunction(ToLongBiFunction<T, U> toLongBiFunction) {
        return toLongBiFunction;
    }
    public static <T> ToLongFunction<T> asToLongFunction(ToLongFunction<T> toLongFunction) {
        return toLongFunction;
    }
    public static <T> UnaryOperator<T> asUnaryOperator(UnaryOperator<T> unaryOperator) {
        return unaryOperator;
    }
    private FunctionCastUtil() {
    }
}

在靜態導入了相關方法之后,我們就可以這樣寫:

Stream.of("A", "", "B").filter(asPredicate(String::isEmpty).negate()).count();

一個更好的解決方案

如果 函數接口本身 就包含一個接收方法引用并將其轉換為某類函數接口的靜態方法,那就更好了。舉例來說,標準的Java Predicated 函數接口就會變成這樣:

@FunctionalInterface
public interface Predicate<T> {
    boolean test(T t);
    default Predicate<T> and(Predicate<? super T> other) {...}
    default Predicate<T> negate() {...}
    default Predicate<T> or(Predicate<? super T> other) {...}
    static <T> Predicate<T> isEqual(Object targetRef) {...}
    // New proposed support method to return a 
    // Predicate view of a Functional Reference 
    public static <T> Predicate<T> of(Predicate<T> predicate) {
        return predicate;
    }
}

因此,我們可以這樣寫:

Stream.of("A", "", "B").filter(Predicate.of(String::isEmpty).negate()).count();

筆者覺得這樣看起來好極了!

快聯系離你最近的Open JDK開發人員,提出你的修改建議吧!

OneAPM 能為您提供端到端的Java 應用性能解決方案,我們支持所有常見的 Java 框架及應用服務器,助您快速發現系統瓶頸,定位異常根本原因。分鐘級部署,即刻體驗,Java 監控從來沒有如此簡單。想閱讀更多技術文章,請訪問OneAPM 官方技術博客。

via: http://blog.oneapm.com/apm-tech/692.html

 本文由用戶 helloyou0 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!