Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function pointers/delegates in Java?

For my Java game server I send the Action ID of the packet which basically tells the server what the packet is for. I want to map each Action ID (an integer) to a function. Is there a way of doing this without using a switch?

like image 574
ryeguy Avatar asked Dec 28 '08 04:12

ryeguy


People also ask

Are delegates function pointers?

A delegate is a type-safe function pointer that can reference a method that has the same signature as that of the delegate. You can take advantage of delegates in C# to implement events and call-back methods. A multicast delegate is one that can point to one or more methods that have identical signatures.

Are there function pointers in Java?

From Java 8 onwards, the lambda expression is introduced which acts as function pointers. Lambda expressions are introduced in Java 8 and are touted to be the biggest feature of Java 8. Lambda expression facilitates functional programming and simplifies the development a lot.

How do you create a function pointer in Java?

Start by defining an interface that defines the method signatures of the method(s) you are pointing to. Next, create methods with the target method signature. The next step is to create variables of the wrapping interface and assign methods to them. The variables will act as a function pointer to be stored or executed.

What are pointers in Java?

A POINTER IS JUST THE ADDRESS OF SOME location in memory. In Java, pointers play an important role behind the scenes in the form of references to objects. A Java variable of object type stores a reference to an object, which is just a pointer giving the address of that object in memory.


2 Answers

What about this one?

HashMap<Integer, Runnable> map = new HashMap<Integer, Runnable>();
map.put(Register.ID, new Runnable() { 
    public void run() { functionA(); }
});
map.put(NotifyMessage.ID, new Runnable() { 
    public void run() { functionB(); }
});
// ...
map.get(id).run();

(If you need to pass some arguments, define your own interface with a function having a suitable parameter, and use that instead of Runnable).

like image 140
Johannes Schaub - litb Avatar answered Oct 14 '22 00:10

Johannes Schaub - litb


Another similar approach could be using Java 8's Suppliers:

Map<Integer, Supplier<T>> suppliers = new HashMap();

suppliers.put(1, () -> methodOne());
suppliers.put(2, () -> methodTwo());

// ...

public T methodOne() { ... }
public T methodTwo() { ... }

// ...

T obj = suppliers.get(id).run();
like image 31
tristobal Avatar answered Oct 13 '22 23:10

tristobal