Add MergedAnnotation.getRoot() method

Update `MergedAnnotation` with a `getRoot()` method that allows the
root direct annotation to be retrieved easily.

Closes gh-22818
This commit is contained in:
Phillip Webb 2019-04-25 14:14:03 -07:00
parent 7cc132b2a9
commit 83cb51aec6
5 changed files with 43 additions and 0 deletions

View File

@ -140,6 +140,13 @@ public interface MergedAnnotation<A extends Annotation> {
@Nullable
MergedAnnotation<?> getParent();
/**
* Get the root annotation, i.e. the {@link #getDepth() depth} {@code 0}
* annotation as directly declared on the source.
* @return the root annotation
*/
MergedAnnotation<?> getRoot();
/**
* Determine if the specified attribute name has a non-default value when
* compared to the annotation declaration.

View File

@ -66,6 +66,11 @@ final class MissingMergedAnnotation<A extends Annotation> extends AbstractMerged
return null;
}
@Override
public MergedAnnotation<?> getRoot() {
return this;
}
@Override
public int getDepth() {
return -1;

View File

@ -171,6 +171,16 @@ final class TypeMappedAnnotation<A extends Annotation> extends AbstractMergedAnn
this.valueExtractor, this.aggregateIndex, this.resolvedRootMirrors);
}
@Override
public MergedAnnotation<?> getRoot() {
if (getDepth() == 0) {
return this;
}
AnnotationTypeMapping rootMapping = this.mapping.getRoot();
return new TypeMappedAnnotation<>(rootMapping, this.source, this.rootAttributes,
this.valueExtractor, this.aggregateIndex, this.resolvedRootMirrors);
}
@Override
public boolean hasDefaultValue(String attributeName) {
int attributeIndex = getAttributeIndex(attributeName, true);

View File

@ -154,6 +154,22 @@ public class MergedAnnotationsTests {
.isEqualTo(ComposedTransactionalComponent.class);
}
@Test
public void getRootWhenNotDirect() {
MergedAnnotations annotations = MergedAnnotations.from(ComposedTransactionalComponentClass.class);
MergedAnnotation<?> annotation = annotations.get(TransactionalComponent.class);
assertThat(annotation.getDepth()).isGreaterThan(0);
assertThat(annotation.getRoot().getType()).isEqualTo(ComposedTransactionalComponent.class);
}
@Test
public void getRootWhenDirect() {
MergedAnnotations annotations = MergedAnnotations.from(ComposedTransactionalComponentClass.class);
MergedAnnotation<?> annotation = annotations.get(ComposedTransactionalComponent.class);
assertThat(annotation.getDepth()).isEqualTo(0);
assertThat(annotation.getRoot()).isSameAs(annotation);
}
@Test
public void collectMultiValueMapFromNonAnnotatedClass() {
MultiValueMap<String, Object> map = MergedAnnotations.from(

View File

@ -78,6 +78,11 @@ public class MissingMergedAnnotationTests {
assertThat(this.missing.getParent()).isNull();
}
@Test
public void getRootReturnsEmptyAnnotation() {
assertThat(this.missing.getRoot()).isSameAs(this.missing);
}
@Test
public void hasNonDefaultValueThrowsNoSuchElementException() {
assertThatNoSuchElementException().isThrownBy(