Search code examples
eventsjava-ee-6cdi

CDI events inheritance


Is there a way of using class inheritance with CDI Events?

Lets say I have something like this:

public class ParentEvent{}

public class ChildEvent extends ParentEvent{}

and something like this:

public class Manager(){
    @Inject 
    private Event<ParrentEvent> event;

    public void foo(){
        event.fire(new ParentEvent());
    }

    public void bar(){
        event.fire(new ChildtEvent());
    }        
}

public class Observer{

      public void observesParent(@Observes ParentEvent event){
          //do something
      }

      public void observesChild(@Observes ChildEvent event){
          //do something
      }
}

In this case both ParentEvent and ChildEvent are processed by observesParent() - due to type of event attribute in Manager class. Is there a way to observe ChildEvent with both observer methods?


Solution

  • The idea of CDI is to use qualifiers in conjunction with events / observers (and not inheritance). Check that chapter in the Weld documentation. The desired behaviour should be easily achievable with something like this:

    public class Manager(){
        @Inject
        @Parent
        private Event<MyEvent> parentEvent;
    
        @Inject
        @Child
        private Event<MyEvent> childEvent; 
    
    // ...
    
        public void foo(){
            event.fire(parentEvent);
        }
    
        public void bar(){
            event.fire(childEvent);
        }
    }
    
    
    public void observeChild(@Observes @Child MyEvent myEvent) { ... }
    public void observeParent(@Observes @Parent MyEvent myEvent) { ... }
    public void observeAll(@Observes MyEvent myEvent) { ... }
    

    This far more flexible than using inheritance...