BAEL-5140 Retrieve field's annotations (#11254)

This commit is contained in:
polomos 2021-10-11 03:30:06 +02:00 committed by GitHub
parent 9c07f794f1
commit 95fdf94aee
6 changed files with 82 additions and 2 deletions

View File

@ -14,6 +14,19 @@
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<assertj-core.version>3.10.0</assertj-core.version>
</properties>
<build>
<finalName>core-java-annotations</finalName>
<resources>

View File

@ -0,0 +1,9 @@
package com.baeldung.readannotations;
public class ClassWithAnnotations {
@FirstAnnotation
@SecondAnnotation
@ThirdAnnotation
private String classMember;
}

View File

@ -0,0 +1,8 @@
package com.baeldung.readannotations;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface FirstAnnotation {
}

View File

@ -0,0 +1,8 @@
package com.baeldung.readannotations;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface SecondAnnotation {
}

View File

@ -0,0 +1,8 @@
package com.baeldung.readannotations;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.SOURCE)
public @interface ThirdAnnotation {
}

View File

@ -0,0 +1,34 @@
package com.baeldung.readannotations;
import org.junit.Test;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import static org.assertj.core.api.Assertions.assertThat;
public class ClassWithAnnotationsUnitTest {
@Test
public void whenCallingGetDeclaredAnnotations_thenOnlyRuntimeAnnotationsAreAvailable() throws NoSuchFieldException {
Field classMemberField = ClassWithAnnotations.class.getDeclaredField("classMember");
Annotation[] annotations = classMemberField.getDeclaredAnnotations();
assertThat(annotations).hasSize(2);
}
@Test
public void whenCallingIsAnnotationPresent_thenOnlyRuntimeAnnotationsAreAvailable() throws NoSuchFieldException {
Field classMemberField = ClassWithAnnotations.class.getDeclaredField("classMember");
assertThat(classMemberField.isAnnotationPresent(FirstAnnotation.class)).isTrue();
assertThat(classMemberField.isAnnotationPresent(SecondAnnotation.class)).isTrue();
assertThat(classMemberField.isAnnotationPresent(ThirdAnnotation.class)).isFalse();
}
@Test
public void whenCallingGetDeclaredAnnotationsOrGetAnnotations_thenSameAnnotationsAreReturned() throws NoSuchFieldException {
Field classMemberField = ClassWithAnnotations.class.getDeclaredField("classMember");
Annotation[] declaredAnnotations = classMemberField.getDeclaredAnnotations();
Annotation[] annotations = classMemberField.getAnnotations();
assertThat(declaredAnnotations).containsExactly(annotations);
}
}