Skip to content

Commit

Permalink
Ìgnore JavaStaticInitializer in springAnnotatedWith
Browse files Browse the repository at this point in the history
  • Loading branch information
rweisleder committed Mar 19, 2024
1 parent e78b706 commit 979dfd7
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import com.tngtech.archunit.core.domain.JavaMember;
import com.tngtech.archunit.core.domain.JavaMethod;
import com.tngtech.archunit.core.domain.JavaParameter;
import com.tngtech.archunit.core.domain.JavaStaticInitializer;
import com.tngtech.archunit.core.domain.properties.CanBeAnnotated;
import org.springframework.core.annotation.MergedAnnotation;
import org.springframework.core.annotation.MergedAnnotations;
Expand Down Expand Up @@ -190,6 +191,11 @@ private static AnnotatedElement asAnnotatedElement(CanBeAnnotated annotated) {
return ((JavaClass) annotated).reflect();
}

if (annotated instanceof JavaStaticInitializer) {
// Contrary to the JLS, ArchUnit considers static initializers to have annotations.
return null;
}

if (annotated instanceof JavaField) {
return ((JavaField) annotated).reflect();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import com.tngtech.archunit.core.domain.JavaMethod;
import com.tngtech.archunit.core.domain.JavaMethodCall;
import com.tngtech.archunit.core.domain.JavaParameter;
import com.tngtech.archunit.core.domain.JavaStaticInitializer;
import com.tngtech.archunit.core.domain.properties.CanBeAnnotated;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Nested;
Expand Down Expand Up @@ -92,6 +93,15 @@ void rejects_class_with_annotation_not_present_on_class() {
assertThat(predicate).rejects(controllerClass);
}

@Test
@SuppressWarnings("OptionalGetWithoutIsPresent")
void rejects_static_initializer() {
JavaClass classWithStaticInitializer = importClass(ClassWithStaticInitializer.class);
JavaStaticInitializer staticInitializer = classWithStaticInitializer.getStaticInitializer().get();
DescribedPredicate<CanBeAnnotated> predicate = springAnnotatedWith(OptionalAutowired.class);
assertThat(predicate).rejects(staticInitializer);
}

@Test
void accepts_field_with_annotation_directly_present_on_field() {
JavaClass classWithFieldAnnotation = importClass(ClassWithFieldAnnotation.class);
Expand Down Expand Up @@ -488,6 +498,12 @@ void methodAccessingAnnotatedMethod() {
}
}

@SuppressWarnings("EmptyClassInitializer")
static class ClassWithStaticInitializer {
static {
}
}

@Retention(RetentionPolicy.RUNTIME)
@Autowired(required = false)
@interface OptionalAutowired {
Expand Down

0 comments on commit 979dfd7

Please sign in to comment.