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?
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:
This far more flexible than using inheritance…