使用 CDI 添加类注释

问题描述 投票:0回答:1

我正在尝试使用 CDI 扩展事件 ProcessAnnotatedType 向注释类型的接口添加新的 annotioion。类似这样的东西:

< T > void processAnnotatedType( @Observes ProcessAnnotatedType< T > pat)
    {
        AnnotatedType< T > annotatedType = pat.getAnnotatedType();
        Arrays.stream( annotatedType.getJavaClass()
                .getInterfaces() )
            .forEach( aClass -> {
                // add annotation to interfaces
            } );

    }

使用构建器可以轻松地在 CDI 和实际 Java 类注释之间添加由 AnnotatedType 抽象层提供的注释,如下所示:

AnnotatedTypeBuilder< T > builder =
            new AnnotatedTypeBuilder< T >().readFromType( annotatedType );
        builder.addToClass( schema );

但是如何在其他地方添加这样的注释呢?喜欢我的例子中的接口吗?我试图使用 Javaassit 添加,但在运行时出现异常:

2023-10-12T13:25:30.324589648Z Caused by: `org.jboss.weld.exceptions.IllegalArgumentException: WELD-001301: Annotation QualifierInstance {....}} is not a qualifier`
java wildfly cdi
1个回答
0
投票

CDI 扩展(在本例中为可移植扩展)旨在对 CDI 发现的类型和 bean 进行操作,并添加/删除/修改与 CDI 相关的数据。 此外,以这种方式更改的(元)数据仅对 CDI“可见”,没有字节码更改或类似的内容。这意味着即使发生了这样的更改,通过 Java 反射内省原始类也不会显示它们。

因此,如果您尝试向任意类添加任意注释,CDI 不是正确的工具,您应该研究一些操作字节码的框架,例如 JavaAssist 或 ByteBuddy 或其他替代方案(较旧的问题,但在其列表中仍然相关) .

© www.soinside.com 2019 - 2024. All rights reserved.