Java equivalent to C # delegates / events: changing event-driven code dynamically

I have a simple Screen class in C # that has a bunch of events (with corresponding delegates) like FadeOutEvent .

I want to port my library to Java, and I found that the event / delegate mechanism is really awkward. In particular, I cannot write code easily, for example:

 if (someVar == someVal) { this.FadeOutComplete += () => { this.ShowScreen(new SomeScreen()); }; } else { this.FadeOutComplete += () => { this.ShowScreen(new SomeOtherScreen()); }; } 

For all of you guys only for Java, in fact, what I'm talking about is the inability to reassign the event processing method in the current class to something else dynamically, without creating new classes ; it seems that if I use interfaces, the current class must implement the interface, and I cannot change the code that is called later.

In C #, usually you have code that:

  • In the constructor / at an early stage, assign an event code for the event
  • Later at runtime, completely remove this code.
  • Change this original handler often to a different handler code

A strategy template can solve this problem (and does), although for this I need additional classes and interfaces; in C #, this is just a declarative event / delegate and I am done.

Is there a way to do this without inner / anonymous classes?

Edit: I just saw this SO question that might help.

+4
source share
1 answer

In most cases, it was the other way around:

 this.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (someVar == someVal) { showSomeScreen(); } else { showSomeOtherScreen(); } } }); 

But you can do something similar to your C # code by delegating two other objects:

 private Runnable delegate; // ... this.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { delegate.run(); } }); // ... if (someVar == someVal) { this.delegate = new Runnable() { @Override public void run() { showSomeScreen(); } }; } else { this.delegate = new Runnable() { @Override public void run() { showSomeOtherScreen(); } }; } 

Delegates were proposed by Microsoft for Java a long time ago, and Sun declined. I don’t remember if anonymous inner classes existed at this time or were chosen as an alternative.

+12
source

All Articles