I have an annotation processor that takes an annotated class and attempts to create a subclass of it:
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();
}
}
This works with classes without type parameters, but I'm not sure how to do so with them. Performing toString
on the type variables will only give the variable name, not the bounds too. Any ideas on how to do this?