从 Java Annotation Processor 访问源代码 [英] Accessing source code from Java Annotation Processor

查看:21
本文介绍了从 Java Annotation Processor 访问源代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 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!

推荐答案

我遇到了一个问题,我必须访问一些源代码(非字符串/非原始常量的初始化代码)并通过访问解决了这个问题通过 Compiler Tree 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();

就是这样!最后, fieldInitiliazer 变量将包含用于初始化常量的确切代码行.通过一些调整,您应该能够使用相同的方法来访问源树中其他元素类型的源代码(即方法、包声明等)

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 Annotation Processor 访问源代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆