title: Events handling with generic handlers in java
body: <p>I have written custom dispathing/handling event system that generally look like this:</p>
  
  <p>Event handler interface:</p>
  
  <pre><code>public interface EventHandler{
  }
  </code></pre>
  
  <p>Base event class:</p>
  
  <pre><code>public abstract class Event&lt;H extends EventHandler&gt; {
      public static Class Type&lt;H&gt; { }
      public abstract void dispatch(H handler);
  }
  </code></pre>
  
  <p>Handler manager:</p>
  
  <pre><code>public class HandlerManager {
      private Map&lt;Event.Type, List&lt;EventHandler&gt;&gt; map = new HashMap&lt;Event.Type, List&lt;EventHandler&gt;&gt;();
      public void register(Event.Type&lt;H&gt; type, H handler) {
          if(map.get(type) == null) { map.put(type, new ArrayList&lt;EventHandler&gt;()); }
          map.get(type).add(handler);
      }
  
      public void fire(Event&lt;H&gt; event) {...}
      ...
  }
  </code></pre>
  
  <p>And everything is working fine but i want to use events like</p>
  
  <pre><code>public class DataChangeEvent&lt;D&gt; extends Event&lt;DataChangeHandler&lt;D&gt;&gt; {
      public static final Type&lt;?&gt; TYPE = new Type&lt;?&gt;();
      D data;
      ...
      public void dispatch(DataChangeHandler&lt;D&gt; handler) {
          handler.onDataChanged(this);
      }
      public D getData() { return data; }
  }
  
  public class DataChangeHandler&lt;D&gt; extends EventHandler {
      void onDataChanged(DataChangeEvent&lt;D&gt; event);
  }
  </code></pre>
  
  <p>and now when I register handler DataChangeHandler with manager that generates events for Strings and for example for Integers, this registered handler will receive both events what causes ClassCastException to occure when I want to read data.
  I understand that generic dont have some special class and that despite of type defined in DataChangeHandler they are stored in the same list in handlers map.</p>
  
  <p>Is there any way to make it work?</p>