我有一个注释处理器的问题。
首先是我的源代码:
@SupportedAnnotationTypes("*")
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class TreeAnnotationProcessor extends AbstractProcessor{
private Trees trees;
private Tree tree;
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
trees = Trees.instance(processingEnv);
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
for (Element element : roundEnv.getRootElements()) {
tree = trees.getTree(element);
}
return true;
}
public Tree getTree() {
return tree;
}
}
This Annotationprocessor收集编译器的树。在这个处理器中,一切都很好。如果我在编译过程之后调用函数getTree,那么树就没有完成。树(节点)的所有子节点都不在。
...
JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, null, null, null, compilationUnits);
TreeAnnotationProcessor treeAnnotationProcessor = new TreeAnnotationProcessor();
task.setProcessors(Collections.singletonList(treeAnnotationProcessor));
task.call();
Tree tree = treeAnnotationProcessor.getTree();
...
谢谢你的帮助。
我找到了一个解决方案。tree接口是由类com.sun.tools.javac.tree.JCTree实现的。这个类实现了一个克隆方法。当我使用此方法时,克隆在编译过程后完成:
@SupportedAnnotationTypes("*")
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class TreeAnnotationProcessor extends AbstractProcessor{
private Trees trees;
private Tree tree;
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
trees = Trees.instance(processingEnv);
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
for (Element element : roundEnv.getRootElements()) {
tree = trees.getTree(element);
try {
Method cloneMethod = tree.getClass().getMethod("clone");
Object cloneTree = cloneMethod.invoke(tree);
this.tree = (Tree) cloneTree;
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
return true;
}
public Tree getTree() {
return tree;
}
}