How can I check the type of a method parameter in an annotation processor?
With pure reflection, this would be easy, but the world of annotation processors seems different. How do I get the from TypeMirror
returned using getParameterTypes()
in String.class
?
In my annotation processor, I want to check if the current method is currently of the exact form:
public boolean someName(String input)
I can check the primitive return type, but the parameter is String
causing problems:
private void processAnnotation(Element method, Messager msg) {
final MyAnnotation ann = method.getAnnotation(MyAnnotation.class);
if (method.getKind() != ElementKind.METHOD) {
error("annotation only for methods", method);
}
Set<Modifier> modifiers = method.getModifiers();
if(!modifiers.contains(Modifier.PUBLIC)) {
error("annotated Element must be public", method);
}
if(modifiers.contains(Modifier.STATIC)) {
error("annotated Element must not be static", method);
}
ExecutableType emeth = (ExecutableType)method.asType();
if(!emeth.getReturnType().getKind().equals(TypeKind.BOOLEAN)) {
error("annotated Element must have return type boolean", method);
}
if(emeth.getParameterTypes().size() != 1) {
error("annotated Element must have exactly one parameter", method);
} else {
TypeMirror param0 = emeth.getParameterTypes().get(0);
// TODO: check if param.get(0) is String
}
}
source to share
We can go through Elements.getTypeElement
to get the type during processing by its canonical name.
Types types = processingEnv.getTypeUtils();
Elements elems = processingEnv.getElementUtils();
TypeMirror param0 = m.getParameterTypes.get(0);
TypeMirror string = elems.getTypeElement("java.lang.String").asType();
boolean isSame = types.isSameType(param0, string);
It is not possible to get a "class" as such, because annotation processing is done at partial compilation, and we cannot load the classes that are compiled.
source to share