Java方法即returns一个函数?

Java method that returns a function?

我正在使用 Guava collections' transform functions,发现自己制作了很多像这样的伪代码的匿名函数:

    Function<T, R> TransformFunction = new Function<T, R>() {
        public R apply(T obj) {
            // do what you need to get R out of T
            return R;
        }
    };

...但由于我需要重复使用其中的一些,我想将常用的放入 class 以便于访问。

不好意思说(因为我不常使用 Java),我想不出如何使 class 方法 return 像这样的函数这个。可以吗?

我认为您想做的是创建一个 public 静态函数,您可以在整个代码中重复使用它。

例如:

  public static final Function<Integer, Integer> doubleFunction = new Function<Integer, Integer>() {
    @Override
    public Integer apply(Integer input) {
      return input * 2;
    }
  };

或者如果你想酷一点就使用 lambdas

public static final Function<Integer, Integer> doubleFunction = input -> input * 2;

简单封装成一个class:

public class MyFunction implements Function<T, R> {
    public R apply(T obj) {
        // do what you need to get R out of T
        return R;
    }
};

然后你可以像这样在客户端代码中使用class:

Function<T, R> TransformFunction = new MyFunction();

如果你的功能相互关联,你也可以将它们封装成一个enum,因为enums可以实现interfaces。