Inherit event handlers
All checks were successful
zdm/event-bus/pipeline/head This commit looks good

When registering an event listener, Event Bus recursively walks the
entire inheritance tree and looks for event handlers.
This commit is contained in:
2022-01-09 14:16:30 +01:00
parent c5607d12ae
commit 7fb633d69f
8 changed files with 149 additions and 6 deletions

View File

@ -0,0 +1,40 @@
package dev.kske.eventbus.core;
import static org.junit.jupiter.api.Assertions.assertSame;
import org.junit.jupiter.api.Test;
/**
* Tests whether event handlers correctly work in the context of an inheritance hierarchy.
*
* @author Kai S. K. Engelbart
* @since 1.3.0
*/
class InheritanceTest extends SimpleEventListenerBase implements SimpleEventListenerInterface {
EventBus bus = new EventBus();
@Test
void test() {
bus.registerListener(this);
var event = new SimpleEvent();
bus.dispatch(event);
assertSame(4, event.getCounter());
}
@Override
void onSimpleEventAbstractHandler(SimpleEvent event) {
event.increment();
}
@Override
public void onSimpleEventInterfaceHandler(SimpleEvent event) {
event.increment();
}
@Event
private void onSimpleEventPrivate(SimpleEvent event) {
event.increment();
}
}

View File

@ -1,9 +1,31 @@
package dev.kske.eventbus.core;
/**
* A simple event for testing purposes.
* A simple event for testing purposes. The event contains a counter that is supposed to be
* incremented when the event is processed by a handler. That way it is possible to test whether all
* handlers that were supposed to be invoked were in fact invoked.
*
* @author Kai S. K. Engelbart
* @since 0.0.1
*/
class SimpleEvent {}
class SimpleEvent {
private int counter;
@Override
public String toString() {
return String.format("SimpleEvent[%d]", counter);
}
void increment() {
++counter;
}
int getCounter() {
return counter;
}
void reset() {
counter = 0;
}
}

View File

@ -0,0 +1,20 @@
package dev.kske.eventbus.core;
/**
* An abstract class defining a package-private and a private handler for {@link SimpleEvent}.
*
* @author Kai S. K. Engelbart
* @since 1.3.0
*/
abstract class SimpleEventListenerBase {
@Event
void onSimpleEventAbstractHandler(SimpleEvent event) {
event.increment();
}
@Event
private void onSimpleEventPrivate(SimpleEvent event) {
event.increment();
}
}

View File

@ -0,0 +1,13 @@
package dev.kske.eventbus.core;
/**
* An interface defining a single handler for {@link SimpleEvent}.
*
* @author Kai S. K. Engelbart
* @since 1.3.0
*/
interface SimpleEventListenerInterface {
@Event
void onSimpleEventInterfaceHandler(SimpleEvent event);
}