gpt4 book ai didi

java - 注释处理器

转载 作者:行者123 更新时间:2023-11-30 08:09:40 25 4
gpt4 key购买 nike

我的 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;
}
}

这个注释处理器收集编译器的树。在这个处理器中一切都很好。如果我在编译过程后调用函数 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 接口(interface)由 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;
}
}

关于java - 注释处理器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30572524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com