Search code examples
javawildflycdi

Adding class annotations using CDI


I'm trying to use CDI extension event ProcessAnnotatedType to add a new annatioion to the interface of annotated type. Something like that:

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

    }

It is easy to add annotation to provided by AnnotatedType abstraction layer between CDI and actual Java class annotation using builder like here:

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

But how to add such annotation somewhere else? Like to interfaces in my case? I was trying to add using Javaassit but get exception in runtime:

2023-10-12T13:25:30.324589648Z Caused by: `org.jboss.weld.exceptions.IllegalArgumentException: WELD-001301: Annotation QualifierInstance {....}} is not a qualifier`

Solution

  • CDI Extensions (Portable extensions in this case) are meant to operate on CDI-discovered types and beans and add/remove/modify CDI-related data. Furthermore, (meta)data changed this way are only "visible" to CDI, there are no bytecode changes or anything like that. This means that even if such change goes through, introspecting the original class via Java reflections will not show them.

    If you are therefore trying to add arbitrary annotation to arbitrary class, CDI is not the right tool and you should instead look into some framework manipulating bytecode such as JavaAssist or ByteBuddy or other alternatives (older question but still relevant in its listings).