Last active
September 24, 2021 10:02
-
-
Save runeflobakk/10f03d4a20ae9ae0b1a0ff20d6333fe3 to your computer and use it in GitHub Desktop.
Use ArchUnit to inspect interfaces and their subclasses
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://twitter.com/nikolaiii/status/1441308118017724424?s=20