lundi 22 janvier 2018

Java annotation could not be found on class if it's the last one

Consider the following code:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface CustomAnnotation {
   String getName();   
}

import lombok.extern.log4j.Log4j2;
import net.jcip.annotations.Immutable;
import org.springframework.stereotype.Component;

// @CustomAnnotation("MyClass") // here the annotation is presented
@Component
@Log4j
@Immutable
// @CustomAnnotation("MyClass") // here the annotation is not presented
public class MyClass {
}

I'm listing out the annotation for MyClass:

MyClass myClass = new MyClass();
if (myClass.getClass() // this gives back the original class, not a proxy
        .getAnnotations()
        .stream()
        .filter(a -> a.getName().contains("My"))
        .anyMatch()) {
    System.out.println("found");
} else {
    System.out.println("not found");
}

  • If I put my annotation in the very first place (or so far it seems that before the @Component annotation, it's presented in the list.
  • If I put it the very last place (or at least after the @Component annotation, it's not presented.

I'm suspecting that something is going on with Spring in this case, but I'm really curious about the root cause.





Aucun commentaire:

Enregistrer un commentaire