Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resolving AliasFor annotation value programatically in Spring

I have an annotation

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface A {
    Class<?> value();
}

and another annotation that uses @AliasFor

@A (Void.class)
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface B {

    @AliasFor(annotation = A.class)
    Class<?> value();
}

which is used on class

@B(D.class)
public class C implements D {
}

If I have an instance of C, how can I programatically resolve A.value() to Class<D>? I'm trying to synthesise the annotation with AnnotationUtils but when I retrieve the value I'm constantly getting Class<Void>.

like image 679
Lovro Pandžić Avatar asked Feb 02 '26 18:02

Lovro Pandžić


1 Answers

After some digging around, the answer is that I've used the wrong class. Instead of AnnotationUtils it can be done with AnnotatedElementUtils:

@Test
public void shouldFindAliasedValue() {

    Class<?> actual = AnnotatedElementUtils.findMergedAnnotation(C.class, A.class).value();

    then(actual).isEqualTo(D.class);
}
like image 172
Lovro Pandžić Avatar answered Feb 04 '26 09:02

Lovro Pandžić



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!