java 返回函数的Java方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29584027/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 15:32:34  来源:igfitidea点击:

Java method that returns a function?

javaguavageneric-collections

提问by ewall

I'm using Guava collections' transform functions, and finding myself making a lot of anonymous functions like this pseudocode:

我正在使用Guava 集合的转换函数,并发现自己制作了很多匿名函数,如以下伪代码:

    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;
        }
    };

...but since I need to reuse some of them, I'd like to put the frequent ones into a class for easy access.

...但由于我需要重用其中的一些,我想将常用的放在一个类中以便于访问。

I'm embarrassed to say (since I don't use Java much), I can't figure out how to make a class method return a function like this. Can you?

不好意思说(因为我不太会用Java),我想不出如何让类方法返回这样的函数。你可以吗?

回答by satnam

I think what you want to do is make a public static function that you can re-use throughout your code.

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

For example:

例如:

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

Or if you want to be cool and use lambdas

或者,如果你想变酷并使用 lambdas

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

回答by Mick Mnemonic

Simply encapsulate it into a 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;
    }
};

Then you can use the class in client code like this:

然后您可以在客户端代码中使用该类,如下所示:

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

If your functions are related to each other, you could also encapsulate them into an enum, because enums can implement interfaces.

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