我有由我的自定义注释注释的类@Inner
。
我想创建一个规则ArchUnit
来检测是否在同一个包或子包中访问了使用此特定注释注释的类。
例如:
包裹:com.example.my.package
包含类:MyInner
带有注释的@Inner
所以规则应该检查是否MyInner
只能从com.example.my.package
or访问com.example.my.package.baz
我有由我的自定义注释注释的类@Inner
。
我想创建一个规则ArchUnit
来检测是否在同一个包或子包中访问了使用此特定注释注释的类。
例如:
包裹:com.example.my.package
包含类:MyInner
带有注释的@Inner
所以规则应该检查是否MyInner
只能从com.example.my.package
or访问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.com/TNG/ArchUnit/commit/5f7fadc0f67ba61e2c9fe94bfe494303780c37d7