我在 Java 中将函数作为对象非常有用,又名以下类型的东西:
Function handle_packet_01 = void handle() {}
我不想使用 Scala,因为我无法忍受它的语法。
是否有任何类型的 hack 可以应用于 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另一个例子和方法的用法引用
关于Java 函数作为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34165431/