1

我有由我的自定义注释注释的类@Inner

我想创建一个规则ArchUnit来检测是否在同一个包或子包中访问了使用此特定注释注释的类。

例如:

包裹:com.example.my.package

包含类:MyInner带有注释的@Inner

所以规则应该检查是否MyInner只能从com.example.my.packageor访问com.example.my.package.baz

4

1 回答 1

0

我发现了这样的规则:

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

于 2020-05-04T10:42:30.717 回答