JavaEE CDI in Weld: Generic Events?

佐手、 提交于 2019-12-05 21:35:12

I guess you can do this with dinamically binding qualifier members. This is what your code would look like:

public abstract class MyHome {

    private EntityType entity;

    @Inject
    Event<EntityCreatedEvent> entityCreatedEvent;

    public void fireCreatedEvent() {
        entityCreatedEvent.select(getTypeBinding()).fire(new EntityCreatedEvent(entity));
    }

    private TypeBinding getTypeBinding() {
        return new TypeBinding() {
        public Class<? extends EntityType> value() {return entity.getClass();}
    };
}

@Qualifier
@Target({ PARAMETER, FIELD })
@Retention(RUNTIME)
public @interface EntityTypeQualifier {
    Class<? extends EntityType> value();
}

public abstract class TypeBinding extends AnnotationLiteral<EntityTypeQualifier> implements EntityTypeQualifier {}

//Observers
public void handleEntityType1Created(@Observes @EntityTypeQualifier(EntityType1.class) EntityCreatedEvent event) {}
public void handleEntityType2Created(@Observes @EntityTypeQualifier(EntityType2.class) EntityCreatedEvent event) {}

As this CDI issue points it is not possible to fire an without having the type of T at runtime.

But, if you have the type of T (i.e. you have an instance) you can use the Event as an Instance, and select the event to be fired using a dynamic type literal.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!