从Java注解处理器访问源$ C ​​$ C [英] Accessing source code from Java Annotation Processor

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

问题描述

我试图从Java注解处理器中访问一个类型的实际原始出处code。这可能不知?谢谢!

I am trying to access the actual original source code of a type from within a Java Annotation Processor. Is this possible somehow? Thanks!

推荐答案

我有一个问题,我必须访问一些源$ C ​​$ C(初始化code为非字符串/非基本不变)得到它经由编译器树访问源$ C ​​$ C解决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。获得初始化源$ C ​​$ C为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变量将包含用于初始化我常数code的准确线(S)。随着一些调整,你应该能够使用相同的配方来访问源代码树的其他元素类型(即方法,包声明等)

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)

有关更多的阅读和实例阅读<一href=\"http://today.java.net/pub/a/today/2008/04/10/source-$c$c-analysis-using-java-6-compiler-apis.html#accessing-the-abstract-syntax-tree-the-compiler-tree-api\">article:来源$ C ​​$ C分析使用Java API的6 。

For more reading and examples read this article: Source Code Analysis Using Java 6 APIs.

这篇关于从Java注解处理器访问源$ C ​​$ C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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