So I have this interface
public interface EventHandler<E extends EventObject>
{
public void handleEvent(E event);
}
and I want to derive classes for it that handle events, like so:
public class WorkingHandler implements EventHandler<MouseEvent>
{
public void handleEvent(MouseEvent event)
{
//handle event
}
}
Above example works fine. But compiler won’t let me implement EventHandler multiple times, due to the
extremely frustrating Type Erasure.
public class NotWorkingHandler implements EventHandler<MouseEvent>, EventHandler<KeyEvent>
{
public void handleEvent(MouseEvent event)
{
//handle mouse event
}
public void handleEvent(KeyEvent event)
{
//handle key event
}
}
Several questions…
- Why does Java not allow Type Erasure? IIRC it is something to do with being compatible with earlier versions of Java, correct?
EDIT: I mean why does Java have Type Erasure (had it the other way around)
-
Is there any sort of “mod”/”extension” (for lack of a better word) or programming languages that allow me to get around Type Erasure? As I am not using older versions of Java I don’t care about my code being compatible with older code.
-
Are there any workarounds, within the Java language, that I can use to get around Type Erasure?
-
If no, what are some alternate ways to code event handling in my program that keeps the compiler happy?
I’m not sure that your understanding of Type Erasure in Java is correct. As explained here, the type of your generic class is lost at runtime.
In response to your questions:
I think a simpler solution would be to so something like this: