gpt4 book ai didi

java - 如何进行 AnnotationProcessor 测试带注释类型的*子类型*?

转载 作者:行者123 更新时间:2023-12-01 05:21:45 27 4
gpt4 key购买 nike

我希望创建一个注释,它将测试带注释的类型(可能是接口(interface))及其所有子类型,如果任何测试的类型是没有无参数构造函数的具体类,则抛出编译错误。我能够测试实际带有注释的类型,没问题。测试子类型是我迷失的地方。我怎样才能做到这一点?源码如下:

NoArgConstructorRequired.java

package mshare.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.TYPE)
public @interface NoArgConstructorRequired {
}

NoArgConststructorRequiredProcessor.java

package mshare.annotation;

import java.util.Set;

import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Messager;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.ExecutableType;
import javax.lang.model.type.TypeVisitor;
import javax.lang.model.util.SimpleTypeVisitor7;
import javax.tools.Diagnostic;

@SupportedAnnotationTypes("mshare.annotation.NoArgConstructorRequired")
@SupportedSourceVersion(SourceVersion.RELEASE_7)
public class NoArgConstructorRequiredProcessor extends AbstractProcessor {
// Tests if the visited type has no args
private static final TypeVisitor<Boolean, Void> NO_ARGS_VISITOR = new SimpleTypeVisitor7<Boolean, Void>() {
@Override
public Boolean visitExecutable(ExecutableType t, Void v) {
return Boolean.valueOf(t.getParameterTypes().isEmpty());
}
};

@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
Messager messager = processingEnv.getMessager();

for (TypeElement typeElement : annotations) {
for (Element element : roundEnv.getElementsAnnotatedWith(typeElement)) {
if (!isOkay(element)) {
messager.printMessage(
Diagnostic.Kind.ERROR,
element.getSimpleName() + " lacks a no-arg constructor",
element
);
}
}
}

return true;
}

private static boolean isOkay(Element element) {
if (element.getModifiers().contains(Modifier.ABSTRACT)) {
// class is not concrete
return true;
}

for (Element subElement : element.getEnclosedElements()) {
if (subElement.getKind() == ElementKind.CONSTRUCTOR) {
if (subElement.asType().accept(NO_ARGS_VISITOR, null).booleanValue()) {
// has a no-arg constructor
return true;
}
}
}

return false;
}
}

最佳答案

也许注释应该标记为 @Inherited ,它将注释标记为“通过子类降序”。

关于java - 如何进行 AnnotationProcessor 测试带注释类型的*子类型*?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10302580/

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