我有一些类被我的自定义注解注释为 @Inner
.
我想创建一个规则,用于 ArchUnit
来检测使用该特定注解的类是否在同一包或子包中被访问。
例如
包: com.example.my.package
包含的类: MyInner
被注解为 @Inner
所以规则应该检查是否 MyInner
只能从 com.example.my.package
或 com.example.my.package.baz
我已经找到了这样的规则。
public class DependencyRules {
@PublicAPI(usage = ACCESS)
public static ArchCondition<JavaClass> accessClassesThatResideInAnUpperPackage() {
return new AccessClassesThatResideInAnUpperPackageCondition();
}
private static class AccessClassesThatResideInAnUpperPackageCondition extends ArchCondition<JavaClass> {
AccessClassesThatResideInAnUpperPackageCondition() {
super("access classes that reside in an upper package");
}
@Override
public void check(final JavaClass clazz, final ConditionEvents events) {
for (JavaAccess<?> access : clazz.getAccessesFromSelf()) {
boolean callToSuperPackage = isCallToSuperPackage(access.getOriginOwner(), access.getTargetOwner());
events.add(new SimpleConditionEvent(access, callToSuperPackage, access.getDescription()));
}
}
private boolean isCallToSuperPackage(JavaClass origin, JavaClass target) {
String originPackageName = getOutermostEnclosingClass(origin).getPackageName();
String targetSubPackagePrefix = getOutermostEnclosingClass(target).getPackageName() + ".";
return originPackageName.startsWith(targetSubPackagePrefix);
}
private JavaClass getOutermostEnclosingClass(JavaClass javaClass) {
while (javaClass.getEnclosingClass().isPresent()) {
javaClass = javaClass.getEnclosingClass().get();
}
return javaClass;
}
}
}
源代码: https:/github.comTNGArchUnitcommit5f7fadc0f67ba61e2c9fe94bfe494303780c37d7。