我有一個很好的使用了具有下述功能的Java對象,又名以下之類的事情:的Java函數作爲對象
Function handle_packet_01 = void handle() {}
我不希望使用Scala的,因爲我不能忍受句法。
是否有任何破解我可以適用於JVM允許我這樣做?怎麼樣一個Eclipse插件?
我在Java中看到了一個類似於運算符重載的東西,我也將安裝該插件。
我有一個很好的使用了具有下述功能的Java對象,又名以下之類的事情:的Java函數作爲對象
Function handle_packet_01 = void handle() {}
我不希望使用Scala的,因爲我不能忍受句法。
是否有任何破解我可以適用於JVM允許我這樣做?怎麼樣一個Eclipse插件?
我在Java中看到了一個類似於運算符重載的東西,我也將安裝該插件。
在Java 8可以引用一個構件的方法如下
MyClass::function
編輯:一個更完整的示例
//For this example I am creating an interface that will serve as predicate on my method
public interface IFilter
{
int[] apply(int[] data);
}
//Methods that follow the same rule for return type and parameter type from IFilter may be referenced as IFilter
public class FilterCollection
{
public static int[] median(int[]) {...}
public int[] mean(int[]) {...}
public void test() {...}
}
//The class that we are working on and has the method that uses an IFilter-like method as reference
public class Sample
{
public static void main(String[] args)
{
FilterCollection f = new FilterCollection();
int[] data = new int[]{1, 2, 3, 4, 5, 6, 7};
//Static method reference or object method reference
data = filterByMethod(data, FilterCollection::median);
data = filterByMethod(data, f::mean);
//This one won't work as IFilter type
//data = filterByMethod(data, f::test);
}
public static int[] filterByMethod(int[] data, IFilter filter)
{
return filter.apply(data);
}
}
此外看一看lambda expressions爲另一實例和方法的使用參考
快速問題,FIlter :: median的類型是什麼? – Lolums
@Lolums我現在已經提供了一個更好更完整的例子。 – KuramaYoko
lambda表達式 – andrewdleach
請閱讀關於java 8 api http: //www.oracle.com/webfolder/technetwork/tutorials/obe/java/Lambda-QuickStart/index.html#overview 此外,您可以使用句柄方法的語法創建接口來模擬此類方法。 – gauee
謝謝,我現在就去閱讀它。由於這隻適用於服務器,因此Java 8很好。 – Lolums