I'm setting up an event system, and I want all my events to extend the Event class I've created. However, I also want to at any point be able to add in an additional setCanceled and isCanceled methods.
Here's an example:
public class Event {}
public interface EventCancelable {
public default void setCanceled(boolean canceled) {...}
public default boolean isCanceled() {...}
}
public class PlayerEvent extends Event {
public Player player;
public PlayerEvent(Player player) {
this.player = player;
}
}
public class PlayerMovementEvent extends PlayerEvent implements EventCancelable {...}
As you can see, I used an interface to add in the methods later. The problem is how I have to store if an event is canceled:
public interface EventCancelable {
Map<Object, Boolean> canceled = new HashMap<>();
public void setCanceled(boolean canceled) {
canceled.put(this, canceled);
}
public boolean isCanceled() {
return canceled.get(this);
}
}
Notice since Java only allows static fields, I have to create a map to store which events are canceled. This works fine, but after a while, this will take up more and more memory considering events are being called very frequently. Is there a way to add in cancelable features without using an interface, and without manually putting the code into every event I want to be able to cancel? I can't use an EventCancelable class, since then the PlayerMovementEvent wouldn't be able to extend PlayerEvent and EventCancelable at the same time, since I don't want all PlayerEvents to be cancelable.
Or is Java smart enough to empty the map of extra events no longer used since the map is only used in the interface with this added as the argument?