在Java中的函数指针数组 [英] Array of function pointers in Java

查看:137
本文介绍了在Java中的函数指针数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读<一个href=\"http://stackoverflow.com/questions/122407/whats-the-nearest-substitute-for-a-function-pointer-in-java\">this问题,我仍然不知道是否有可能继续指向方法Java中的数组,如果有谁知道,如果这是可能的,或者不是这将是一个真正的帮助。我试图找到保持字符串和相关功能的列表,如果没有的写作数百乱七八糟的优雅的解决方案。

I have read this question and I'm still not sure whether it is possible to keep pointers to methods in an array in Java, if anyone knows if this is possible or not it would be a real help. I'm trying to find an elegant solution of keeping a list of Strings and associated functions without writing a mess of hundreds of 'if's.

干杯

推荐答案

Java没有函数指针本身(或C#的说法代表)。这种事情往往是匿名的子类实现。

Java doesn't have a function pointer per se (or "delegate" in C# parlance). This sort of thing tends to be done with anonymous subclasses.

public interface Worker {
  void work();
}

class A {
  void foo() { System.out.println("A"); }
}

class B {
  void bar() { System.out.println("B"); }
}

A a = new A();
B b = new B();

Worker[] workers = new Worker[] {
  new Worker() { public void work() { a.foo(); } },
  new Worker() { public void work() { b.bar(); } }
};

for (Worker worker : workers) {
  worker.work();
}

这篇关于在Java中的函数指针数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆