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

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

问题描述

我已阅读这个问题而且我仍然不确定是否可以在 Java 中将指向方法的指针保留在数组中.如果有人知道这是否可能(或不可能),那将是真正的帮助.我试图找到一个优雅的解决方案,保留一个 String 和相关函数的列表,而无需编写成百上千的 if 语句.

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 statements.

干杯

推荐答案

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天全站免登陆