Fork me on GitHub

进阶注解处理器 processor (二)

什么是 AST

AST(Abstract Syntax Tree 抽象语法树)是一种用来描述程序代码语法结构的树形表示方式,语法树的每一个节点都代表着程序代码中的一个语法结构,例如包、类型、修饰符、运算符、接口、返回值,甚至代码注释等都可以是一个语法结构。

什么是 JCTree

JCTree是语法树元素的基类,它包含两个属性:
type:表示语法结构的类型。
pos:用于指明当前语法树节点(JCTree)在语法树中的位置,因此不能直接用new关键字来创建语法树节点,即使创建了也没有意义,而要用TreeMaker来进行操作。

1
2
3
4
5
public abstract class JCTree implements Tree, Cloneable, DiagnosticPosition {
public int pos;
public Type type;
...
}

JCTree 有很多子类,eg:
JCStatement、JCClassDecl、JCMethodDecl、JCVariableDecl、JCModifiers、JCExpression …
在后续多少都会用到。

什么是 TreeMaker

TreeMaker创建语法树节点的所有方法,创建时会为创建出来的JCTree设置pos字段,所以必须用上下文相关的TreeMaker对象来创建语法树节点,而不能直接new语法树节点。

1
2
3
Context context = ((JavacProcessingEnvironment) processingEnv).getContext();
TreeMaker treeMaker = TreeMaker.instance(context);
// ...

怎么使用 TreeMaker

部分方法示例:
TreeMaker.MethodDef
用于创建方法定义语法树节点(JCMethodDecl)

1
2
3
4
5
6
7
8
9
10
public JCMethodDecl MethodDef(JCModifiers mods, Name name,
JCExpression returntype, List<JCTypeParameter> typarams,
List<JCVariableDecl> params, List<JCExpression> thrown,
JCBlock body, JCExpression defaultValue){
JCMethodDecl tree = new JCMethodDecl(mods, name,
returntype, typarams, params, thrown, body,
defaultValue, null);
tree.pos = pos;
return tree;
}

TreeMaker.VarDef
用于创建字段/变量定义语法树节点(JCVariableDecl)

1
2
3
4
5
6
public JCVariableDecl VarDef(JCModifiers mods, Name name, JCExpression vartype, 
JCExpression init) {
JCVariableDecl tree = new JCVariableDecl(mods, name, vartype, init, null);
tree.pos = pos;
return tree;
}

TreeMaker.Return
用于创建return语句语法树节点(JCReturn)

1
2
3
4
5
public JCReturn Return(JCExpression expression) {
JCReturn jcReturn= new JCReturn(expression);
jcReturn.pos = this.pos;
return jcReturn;
}

结语

以上是与JCTree的初次会面,后续逐步进阶~

-------------本文结束感谢您的阅读-------------
如果您对博主的原创满意,欢迎您继续支持下博主~