我的AnnotationProcessor有问题。
首先是我的源代码:
@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;
}
}
此Annotationprocessor收集编译器的树。在这个处理器一切都很好。如果我在编译过程之后调用funktion getTree,那么Tree就不完整了。树(节点)的所有孩子都离开了。
...
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();
...
感谢您的帮助。
答案 0 :(得分:1)
我找到了解决方案。 Tree接口由类com.sun.tools.javac.tree.JCTree实现。该类实现了一个clone-Method。当我使用此方法时,克隆在编译过程完成后完成:
@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;
}
}