Java 函数作为对象

Java Functions as Objects

我在 Java 中将函数作为对象非常有用,也就是下面这样的事情:

Function handle_packet_01 = void handle() {}

我不想用Scala,因为我受不了语法。

是否有任何类型的 hack 可以应用于 JVM 以允许我执行此操作? Eclipse 插件怎么样?

我在 Java 中看到了类似的运算符重载问题,我也打算为此安装插件。

在Java8中可以引用成员方法如下

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 以获取方法参考的另一个示例和用法