Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of function pointers in Java [duplicate]

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.

Cheers

like image 720
Waltzy Avatar asked May 02 '10 01:05

Waltzy


2 Answers

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();
}
like image 183
cletus Avatar answered Sep 19 '22 18:09

cletus


You can achieve the same result with the functor pattern. For instance, having an abstract class:

abstract class Functor
{
  public abstract void execute();
}

Your "functions" would be in fact the execute method in the derived classes. Then you create an array of functors and populate it with the apropriated derived classes:

class DoSomething extends Functor
{
  public void execute()
  {
    System.out.println("blah blah blah");
  }
}

Functor [] myArray = new Functor[10];
myArray[5] = new DoSomething();

And then you can invoke:

myArray[5].execute();
like image 36
Fabio Ceconello Avatar answered Sep 19 '22 18:09

Fabio Ceconello