Java函数作为对象

时间:2015-12-08 20:29:46

标签: java function jvm

我非常善于将函数用作Java中的对象,也就是以下类型的东西:

Function handle_packet_01 = void handle() {}

我不想使用Scala,因为我无法忍受语法。

是否有任何类型的黑客可以应用于JVM以允许我这样做? Eclipse插件怎么样?

我在Java中看到了类似的操作符重载,我也将安装插件。

1 个答案:

答案 0 :(得分:1)

在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了解另一个示例和方法参考

的用法