什么是Java中函数指针的最接近的替代品?

本文翻译自:What's the nearest substitute for a function pointer in Java?

I have a method that's about ten lines of code. 我有一个大约十行代码的方法。 I want to create more methods that do exactly the same thing, except for a small calculation that's going to change one line of code. 我想创建更多完全相同的方法,除了一个会改变一行代码的小计算。 This is a perfect application for passing in a function pointer to replace that one line, but Java doesn't have function pointers. 这是传递函数指针以替换该行的完美应用程序,但Java没有函数指针。 What's my best alternative? 什么是我最好的选择?


#1楼

参考:https://stackoom.com/question/VqJ/什么是Java中函数指针的最接近的替代品


#2楼

Anonymous inner class 匿名内部阶级

Say you want to have a function passed in with a String param that returns an int . 假设您希望使用返回intString参数传入函数。
First you have to define an interface with the function as its only member, if you can't reuse an existing one. 首先,如果不能重用现有的接口,则必须定义一个以函数为唯一成员的接口。

interface StringFunction {
    int func(String param);
}

A method that takes the pointer would just accept StringFunction instance like so: 获取指针的方法只接受StringFunction实例,如下所示:

public void takingMethod(StringFunction sf) {
   int i = sf.func("my string");
   // do whatever ...
}

And would be called like so: 会像这样被称为:

ref.takingMethod(new StringFunction() {
    public int func(String param) {
        // body
    }
});

EDIT: In Java 8, you could call it with a lambda expression: 编辑:在Java 8中,您可以使用lambda表达式调用它:

ref.takingMethod(param -> bodyExpression);

#3楼

For each "function pointer", I'd create a small functor class that implements your calculation. 对于每个“函数指针”,我将创建一个实现计算的小型仿函数类 Define an interface that all the classes will implement, and pass instances of those objects into your larger function. 定义所有类将实现的接口,并将这些对象的实例传递给更大的函数。 This is a combination of the " command pattern ", and " strategy pattern ". 这是“ 命令模式 ”和“ 策略模式 ”的组合。

@sblundy's example is good. @ sblundy的例子很好。


#4楼

You need to create an interface that provides the function(s) that you want to pass around. 您需要创建一个接口,提供您想要传递的功能。 eg: 例如:

/**
 * A simple interface to wrap up a function of one argument.
 * 
 * @author rcreswick
 *
 */
public interface Function1<S, T> {

   /**
    * Evaluates this function on it's arguments.
    * 
    * @param a The first argument.
    * @return The result.
    */
   public S eval(T a);

}

Then, when you need to pass a function, you can implement that interface: 然后,当您需要传递函数时,您可以实现该接口:

List<Integer> result = CollectionUtilities.map(list,
        new Function1<Integer, Integer>() {
           @Override
           public Integer eval(Integer a) {
              return a * a;
           }
        });

Finally, the map function uses the passed in Function1 as follows: 最后,map函数使用传入的Function1,如下所示:

   public static <K,R,S,T> Map<K, R> zipWith(Function2<R,S,T> fn, 
         Map<K, S> m1, Map<K, T> m2, Map<K, R> results){
      Set<K> keySet = new HashSet<K>();
      keySet.addAll(m1.keySet());
      keySet.addAll(m2.keySet());

      results.clear();

      for (K key : keySet) {
         results.put(key, fn.eval(m1.get(key), m2.get(key)));
      }
      return results;
   }

You can often use Runnable instead of your own interface if you don't need to pass in parameters, or you can use various other techniques to make the param count less "fixed" but it's usually a trade-off with type safety. 如果您不需要传入参数,您通常可以使用Runnable而不是您自己的接口,或者您可以使用各种其他技术使参数计数不那么“固定”,但它通常是类型安全的权衡。 (Or you can override the constructor for your function object to pass in the params that way.. there are lots of approaches, and some work better in certain circumstances.) (或者你可以覆盖你的函数对象的构造函数,以这种方式传递params ..有很多方法,有些方法在某些情况下更好。)


#5楼

You may also be interested to hear about work going on for Java 7 involving closures: 您可能也有兴趣了解Java 7涉及闭包的工作:

What's the current state of closures in Java? Java中当前的闭包状态是什么?

http://gafter.blogspot.com/2006/08/closures-for-java.html http://gafter.blogspot.com/2006/08/closures-for-java.html
http://tech.puredanger.com/java7/#closures http://tech.puredanger.com/java7/#closures


#6楼

Sounds like a strategy pattern to me. 听起来像是一种策略模式。 Check out fluffycat.com Java patterns. 查看fluffycat.com Java模式。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值