Java 8 introduces a new feature called default methods which looks like this:
interface A {
default int getInt() {
return 0;
}
}
However, if we add multiple methods:
class Event{...}
class EventA extends Event{...}
class EventAData{}
interface A {
default void handleEvent(Event event) {
if(event instanceof EventA) {
handleData(((EventA) event).getData());
}
}
default void handleData(EventAData data) {
handleEvent(new EventA(data));
}
}
handleEvent()
checks if the event is of class EventA and by default implements a legacy way to handle EventA. handleData()
converts the data into an Event and uses the super new method handleEvent()
to handle the data.
The problem I see is that, when neither of them was implemented, the two methods would call each other, resulting in a stack overflow error. I would probably use reflection to check if the caller is the default handleEvent()
and return if it is.
Is it okay to do so? If not, why?
EDIT: fixed a typo, handleEventA
should be handleData