参考 【Groovy】编译时元编程 ( 编译时元编程引入 | 声明需要编译时处理的类 | 分析 Groovy 类的 AST 语法树 ) 三、分析 Groovy 类的 AST 语法树 博客章节 , 分析
class Student{
def name
def hello(){
println "hello"
}
}
类的 AST 语法树中的 hello 方法对应的 MethodNode 节点 ;
该 MethodNode 节点信息如下 , 关注该 MethodNode 节点下的 code 字段 ,
MethodNode 节点原型如下 :
/**
* 表示方法声明
*
* @author <a href="mailto:james@coredevelopers.net">James Strachan</a>
* @author Hamlet D'Arcy
* @version $Revision$
*/
public class MethodNode extends AnnotatedNode implements Opcodes {
public static final String SCRIPT_BODY_METHOD_KEY = "org.codehaus.groovy.ast.MethodNode.isScriptBody";
private final String name;
private int modifiers;
private boolean syntheticPublic;
private ClassNode returnType;
private Parameter[] parameters;
private boolean hasDefaultValue = false;
private Statement code;
private boolean dynamicReturnType;
private VariableScope variableScope;
private final ClassNode[] exceptions;
private final boolean staticConstructor;
// type spec for generics
private GenericsType[] genericsTypes = null;
private boolean hasDefault;
// cached data
String typeDescriptor;
}
编译时方法拦截需要使用 MethodNode 中的 private Statement code;
成员 , 根据下图 AST 语法树分析
该成员的实际类型是 BlockStatement ;
BlockStatement 原型如下 :
/**
* 语句列表和范围。
*
* @author <a href="mailto:james@coredevelopers.net">James Strachan</a>
* @version $Revision$
*/
public class BlockStatement extends Statement {
private List<Statement> statements = new ArrayList<Statement>();
private VariableScope scope;
}
BlockStatement 中的 List<Statement> statements
成员就是方法节点及相关语句 ;
替换 List<Statement> statements
集合中的元素 , 就可以对方法进行拦截 ;