問題描述
我正在嘗試從 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.
這篇關于從 Java 注釋處理器訪問源代碼的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!