title: JavaEE CDI in Weld: Generic Events?
body: <p>I have an idea for a specific event handling based on generics, but seems like Weld can't handle them. I asked google but couldn't find an alternative CDI extension for this. </p>
  
  <p><strong>Question</strong>: is there a CDI extension, that can handle event propagation of generic-typed events? </p>
  
  <p>In the following the explicit problem I have.</p>
  
  <p>I have three general events, EntityCreated, EntityChanged and EntityDeleted. The base class for them is defined like this: </p>
  
  <pre><code>public abstract class DatabaseEvent&lt;TargetType&gt; {
  
      public TargetType target;
  
      public DatabaseEvent(TargetType target) {
          this.target = target;
      }
  }
  </code></pre>
  
  <p>The events then are simple inherited classes:</p>
  
  <pre><code>public class EntityCreatedEvent&lt;TargetType&gt; extends DatabaseEvent&lt;TargetType&gt; {
  
      public EntityCreatedEvent(TargetType target) {
          super(target);
      }
  }
  </code></pre>
  
  <p>I fire them like this:</p>
  
  <pre><code>public abstract class MyHome&lt;EntityType&gt; {
  
      private EntityType entity;
  
      @Inject
      Event&lt;EntityCreatedEvent&lt;EntityType&gt;&gt; entityCreatedEvent;
  
      public void fireCreatedEvent() {
          EntityCreatedEvent&lt;EntityType&gt; payload = new EntityCreatedEvent&lt;EntityType&gt;(entity);
          entityCreatedEvent.fire(payload);
      }
  }
  </code></pre>
  
  <p>I want to observe them like this:</p>
  
  <pre><code>public void handleProjectCreated(@Observes EntityCreatedEvent&lt;Project&gt; event) { ... }
  </code></pre>
  
  <p>When launching the server Weld tells me it can't handle generic-typed events. The CDI-way of doing things would be to use additional qualifiers instead of the generics to distiguish them, e.g.:</p>
  
  <pre><code>public void handleProjectCreated(@Observes @ProjectEvent EntityCreatedEvent event) { ... }
  </code></pre>
  
  <p>However, I fire the events from that <code>MyHome</code> base class, where I can't just fire with the <code>@ProjectEvent</code>: it might not be a project but another type.</p>
  
  <p>My solution up to now is to skip that typing altogether and handle them like this:</p>
  
  <pre><code>public void handleProjectCreated(@Observes EntityCreatedEvent event) { 
      if(event.target instanceof Project) { ... }
  }
  </code></pre>
  
  <p>This solution is okay, but not perfect.</p>