Java 函数作为对象

标签 java function jvm

我在 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/

相关文章:

python - 如何在没有 list.extend 方法和没有 '+' 运算符的情况下扩展列表

c - C中标识符函数位置问题

javascript - JS : Split function into kind of module parts

java - 有没有办法判断一个类是否已经加载到jvm中?

java - 执行器服务中的依赖线程 - Java

Java 新手编码。添加显示消息

java - JVM稳定但系统内存增加

java - 计算 JVM 中不可变对象(immutable对象)的数量

java - Linux liveUSB 导致 init.d 脚本出错

Java外部类静态初始化