gpt4 book ai didi

java - ArchUnit 规则检查是否在同一包或子包中访问类?

转载 作者:行者123 更新时间:2023-12-01 16:56:39 25 4
gpt4 key购买 nike

我有由我的自定义注释注释的类 @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.com/TNG/ArchUnit/commit/5f7fadc0f67ba61e2c9fe94bfe494303780c37d7

关于java - ArchUnit 规则检查是否在同一包或子包中访问类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61577882/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com