我有一个注释处理器,它接受一个带注释的类并尝试创建它的子类:
package test;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.TypeSpec;
import java.io.IOException;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.ProcessingEnvironment;
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.Modifier;
import javax.lang.model.element.TypeElement;
@SupportedAnnotationTypes("java.lang.SuppressWarnings")
@SupportedSourceVersion(SourceVersion.RELEASE_7)
public class BSProcessor extends AbstractProcessor {
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnvironment) {
for (TypeElement baseClassAnnotation : annotations) {
for (Element annotatedElement : roundEnvironment.getElementsAnnotatedWith(baseClassAnnotation)) {
handleAnnotatedTypeElement((TypeElement) annotatedElement);
}
}
return true;
}
private void handleAnnotatedTypeElement(TypeElement annotatedTypeElement) {
try {
javaFile(annotatedTypeElement).writeTo(System.out);
} catch (IOException e) {
e.printStackTrace();
}
}
private JavaFile javaFile(TypeElement annotatedTypeElement) {
return JavaFile.builder(packageName(annotatedTypeElement), typeSpec(annotatedTypeElement))
.build();
}
private TypeSpec typeSpec(TypeElement annotatedTypeElement) {
return TypeSpec.classBuilder(className(annotatedTypeElement))
.addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
.build();
}
private ClassName className(TypeElement annotatedTypeElement) {
return ClassName.get(packageName(annotatedTypeElement), String.format("AutoGenerated_%s",
annotatedTypeElement.getSimpleName()));
}
private String packageName(TypeElement annotatedTypeElement) {
return annotatedTypeElement.getEnclosingElement().toString();
}
}
这适用于没有类型参数的类,但我不确定如何使用它们。对类型变量执行toString
只会给出变量名称,而不是边界。关于如何做到这一点的任何想法?