Class Cast Exception when casting an elemental2.dom.Event to elemental2.dom.CustomEvent in GWT

70 views Asked by At

I am using elemental2 (GWT) to register for a specific custom event of type CustomEvent - the listener gets called after I dispatch the event but I get a ClassCastException in the browser when I try to cast from Event (the class type of the eventListener) to CustomEvent (which is what I sent and a subclass of Event).

Event receiving code:

DomGlobal.window.addEventListener("mycustomevent", event ->
{
  CustomEvent<String> customEvent=(CustomEvent<String>)event;
  String myDetails = customEvent.detail;
}

GWT code compiles without problems and evrything runs in the browser correctly up to the cast from elemental2.dom.Event to elemental2.dom.CustomEvent. At that point I get the ClassCastException.

This is how I construct the CustomEvent and fire it:

CustomEventInit<String> eventInit = CustomEventInit.create();
eventInit.setDetail("my message");
CustomEvent<String> event = new CustomEvent<>("mycustomevent", eventInit);
DomGlobal.window.parent.dispatchEvent(event);

I looked at the actual type that is received by the listener and the interesting thing is that the class name I am being returned is com.google.core.client.JavaScriptObject and not elemental2.dom.Event as I would have expected from the interface signature.

event.getClass().getName();

Also interesting is that I can use the received event as if it was of type elemental2.dom.Event anyway.

The workaround which is working for me at the moment for getting the detail member of the Customer event is to fallback to JSNI.

public final native String getDetail(Event e)/*-{
        return e.detail;
    }-*/;

This will return the detail of the CustomEvent. Is there an alternative way?

1

There are 1 answers

0
Robert Newton On BEST ANSWER

In your case you will need to get GWT's runtime to skip the cast checking that it normally does.

CustomEvent<String> customEvent = Js.uncheckedCast(event);

This answer to another question discusses casting in GWT