从 Java 注释处理器访问源代码
我正在尝试从 Java 注释处理器中访问某个类型的实际原始源代码.这有可能吗?谢谢!
I am trying to access the actual original source code of a type from within a Java Annotation Processor. Is this possible somehow? Thanks!
推荐答案
我遇到了一个问题,我必须访问一些源代码(非字符串/非原始常量的初始化代码)并通过访问解决了它通过 编译器树 API.
I had a problem where I had to access some source code (the initializer code for a non-String/non-primitive constant) and got it solved by accessing the source code via the Compiler Tree API.
这是一般配方:
1.创建自定义 TreePathScanner:
private static class CodeAnalyzerTreeScanner extends TreePathScanner<Object, Trees> {
private String fieldName;
private String fieldInitializer;
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
public String getFieldInitializer() {
return this.fieldInitializer;
}
@Override
public Object visitVariable(VariableTree variableTree, Trees trees) {
if (variableTree.getName().toString().equals(this.fieldName)) {
this.fieldInitializer = variableTree.getInitializer().toString();
}
return super.visitVariable(variableTree, trees);
}
<强>2.在您的 AbstractProcessor 中,通过覆盖 init 方法保存对当前编译树的引用:
@Override
public void init(ProcessingEnvironment pe) {
super.init(pe);
this.trees = Trees.instance(pe);
}
3.获取 VariableElement 的初始化源代码(在您的情况下为枚举):
// assuming theClass is a javax.lang.model.element.Element reference
// assuming theField is a javax.lang.model.element.VariableElement reference
String fieldName = theField.getSimpleName().toString();
CodeAnalyzerTreeScanner codeScanner = new CodeAnalyzerTreeScanner();
TreePath tp = this.trees.getPath(theClass);
codeScanner.setFieldName(fieldName);
codeScanner.scan(tp, this.trees);
String fieldInitializer = codeScanner.getFieldInitializer();
就是这样!最后 fieldInitializer 变量将包含用于初始化我的常量的确切代码行.通过一些调整,您应该能够使用相同的配方来访问源树中其他元素类型的源代码(即方法、包声明等)
And that's it! In the end the fieldInitiliazer variable is going to contain the exact line(s) of code used to initialize my constant. With some tweaking you should be able to use the same recipe to access the source code of other element types in the source tree (i.e. methods, package declarations, etc)
有关更多阅读和示例,请阅读此 文章:来源使用 Java 6 API 进行代码分析.
For more reading and examples read this article: Source Code Analysis Using Java 6 APIs.
相关文章