2010-10-11 46 views
10

我需要等的接口:的Java:一般功能X-> y異質界面

interface Function<X,Y> { 
    Y eval(X obj); 
} 

有沒有這樣的事情在Java中已經或者我需要確定自己?

+1

可能重複的結果類型:有沒有地圖功能? ](http://stackoverflow.com/questions/3907394/java-is-there-a-map-function) – Riduidel 2010-10-11 15:08:10

+2

@Riduidel:它是如何是同一個問題?這是一個完全不同的問題。 – Albert 2010-10-11 15:15:27

+0

這可能是Java被基因聚合時最明顯的疏忽。 – 2013-03-18 13:41:12

回答

2

有一個內置接口像這樣,儘管它只與Java 8兼容急性呼吸窘迫綜合徵。你可以找到它here

從Javadoc中:

public interface Function<T,R>

表示一個接受一個參數併產生一個結果的功能。

這是一個功能接口,其功能方法是apply(Object)

類型參數:
T - 輸入到功能
R類型 - 函數[Java的

13

退房番石榴,它有一個Function interface

public interface Function<F, T> { 
    /** 
    * Applies the function to an object of type {@code F}, resulting in an object of  type {@code T}. 
    * Note that types {@code F} and {@code T} may or may not be the same. 
    * 
    * @param from the source object 
    * @return the resulting object 
    */ 
    T apply(@Nullable F from); 

    /** 
    * Indicates whether some other object is equal to this {@code Function}. This  method can return 
    * {@code true} <i>only</i> if the specified object is also a {@code Function} and, for every 
    * input object {@code o}, it returns exactly the same value. Thus, {@code 
    * function1.equals(function2)} implies that either {@code function1.apply(o)} and {@code 
    * function2.apply(o)} are both null, or {@code function1.apply(o).equals(function2.apply(o))}. 
    * 
    * <p>Note that it is always safe <i>not</i> to override {@link Object#equals}. 
    */ 
    boolean equals(@Nullable Object obj); 
} 
0

事實上,考慮到你的目標是你,而不是Sun/Oracle的一個,你應該定義自己的接口(因爲它規定了合同你希望你的接口的實現者fullfil)。但是,如果某個框架已經存在這樣的接口,並且其目的與您的目的相同,您可以使用它的定義,但是要謹慎。

5

不幸的是,核心Java庫中沒有這樣的東西。因此,許多庫定義了自己的類似功能的接口。如果您恰好已經使用過這樣的庫,則可以重新使用它使用的功能。

+0

我知道答案是舊的。但是從Java 8+開始,這是可能的。 https://www.leveluplunch.com/java/examples/java-util-function-function-example/ – Eternalcode 2017-06-13 20:46:55

2

可以使用這樣的庫如Apache Commons Functor具有實用的功能,如:

UnaryFunction

T evaluate(A obj); 

BinaryFunction

T evaluate(L left, R right);