How to check using ArchUnit if there is any use of reflection in the source code?

44 Views Asked by At

I want to write a JUnit Test Case using ArchUnit to check if there is usage of reflection in the source that is written by the developer and fail the test case if so. How can I achieve this using ArchUnit? I am using a Kotlin based Application in Spring Boot.

I checked ArchUnit's documentation and can't seem to find a way to do this unfortunately. I am doubting if this is even possible.

1

There are 1 best solutions below

0
Martin Theiss On

Maybe check if there is a usage of java.lang.reflect

package de.solitics.demo;

import com.tngtech.archunit.junit.AnalyzeClasses;
import com.tngtech.archunit.junit.ArchTest;
import com.tngtech.archunit.lang.ArchRule;
import com.tngtech.archunit.lang.syntax.ArchRuleDefinition;

@AnalyzeClasses
public class ReflectionTests {
    @ArchTest
    public static final ArchRule myRule = ArchRuleDefinition.theClass(ReflectionTests.class).should()
            .onlyDependOnClassesThat().resideOutsideOfPackage("java.lang.reflect");

    public static void aMethodUsesReflection() throws Exception {
        ReflectionTests.class.getMethod("aMethod").invoke(new ReflectionTests());
    }

    public void aMethod() {
    }
}