Skip to content

Instantly share code, notes, and snippets.

@runeflobakk
Last active September 24, 2021 10:02
Show Gist options
  • Save runeflobakk/10f03d4a20ae9ae0b1a0ff20d6333fe3 to your computer and use it in GitHub Desktop.
Save runeflobakk/10f03d4a20ae9ae0b1a0ff20d6333fe3 to your computer and use it in GitHub Desktop.
Use ArchUnit to inspect interfaces and their subclasses
import com.tngtech.archunit.core.domain.JavaClass;
import com.tngtech.archunit.core.importer.ClassFileImporter;
import org.junit.jupiter.api.Test;
import static java.util.function.Function.identity;
import static java.util.function.Predicate.not;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toMap;
class InterfacesAndImplementors {
@Test
void list() {
var myCode = new ClassFileImporter().importPackages("my.package");
var interfacesAndImplementors = myCode.stream()
.filter(JavaClass::isInterface)
.filter(not(JavaClass::isAnnotation))
.collect(toMap(identity(), JavaClass::getAllSubclasses));
interfacesAndImplementors.forEach((ifc, implementors) -> {
if (implementors.size() == 0) {
System.out.println("Nothing implements " + ifc.getName() + "!");
} else if (implementors.size() == 1) {
System.out.println("Interface " + ifc.getName() + " is implemented by a single class: " + implementors.stream().map(JavaClass::getName).collect(joining()));
} else {
System.out.println("Interface " + ifc.getName() + " is implemented by multiple classes");
}
});
}
}
@runeflobakk
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment