这绝对是可能的。我会使用TreeAPI。
// In your annotation processor you get it's instance using
// processingEnv
Trees trees = Trees.instance(env);
现在,如果您必须使用TreePathScanner. 因此,例如获取TreePath您的元素:
TreePath path = trees.getPath(element);
现在遍历您的TreePathScanner:
new ReturnTypeCheckingScanner().scan(path, null);
现在你的TreePathScanner实现:
public class ReturnTypeCheckingScanner extends TreePathScanner<Void, Void> {
@Override
public Void visitMethod(MethodTree methodTree, Void aVoid) {
Tree returnType = methodTree.getReturnType();
if(invalidReturnType(returnType)) {
trees.printMessage(
ERROR,
"Invalid return type",
returnType,
getCurrentPath().getCompilationUnit()
);
}
return aVoid;
}
}
直接使用Messager和ElementAPI应该也是可以的。但是您必须弄清楚,如何获取 ExecutableElement.getReturnType() 的元素(类型为TypeMirror)。