当前位置:网站首页>[groovy] compile time meta programming (AST syntax tree conversion with annotations | define annotations and use groovyasttransformationclass to indicate ast conversion interface | ast conversion inte
[groovy] compile time meta programming (AST syntax tree conversion with annotations | define annotations and use groovyasttransformationclass to indicate ast conversion interface | ast conversion inte
2022-07-06 00:34:00 【Programmer community】
List of articles
- One 、 Use annotations to AST Syntax tree conversion
- 1、 Define annotations and use GroovyASTTransformationClass Indicate the AST Adapter
- 2、AST Implementation of conversion interface
- 3、 Definition Groovy Class and use @Compile Annotations modify the methods that need to be intercepted
- 4、 Execution results
One 、 Use annotations to AST Syntax tree conversion
1、 Define annotations and use GroovyASTTransformationClass Indicate the AST Adapter
First , Definition Compile annotation , The annotation name is any string , @Target(ElementType.METHOD)
Indicates that the annotation acts on the method , @GroovyASTTransformationClass("MyASTTransformation")
Indicates that the node modified by this annotation corresponds to AST The implementation class of the conversion interface is MyASTTransformation
;
import org.codehaus.groovy.transform.GroovyASTTransformationClassimport java.lang.annotation.ElementTypeimport java.lang.annotation.Target/** * This annotation works on methods */@Target(ElementType.METHOD)@GroovyASTTransformationClass("MyASTTransformation")@interface Compile {
}
2、AST Implementation of conversion interface
then , Realization MyASTTransformation class , Inheritance of such kind ASTTransformation Interface ;
import org.codehaus.groovy.ast.ASTNodeimport org.codehaus.groovy.ast.builder.AstBuilderimport org.codehaus.groovy.ast.stmt.BlockStatementimport org.codehaus.groovy.control.SourceUnitimport org.codehaus.groovy.transform.ASTTransformationimport org.codehaus.groovy.transform.GroovyASTTransformation@GroovyASTTransformationclass MyASTTransformation implements ASTTransformation {
/** * Compile time processing * @param nodes AST Abstract syntax tree node , yes ASTNode An array type * @param source Source unit , You can get the source file through this object */ @Override void visit(ASTNode[] nodes, SourceUnit source) {
// obtain Groovy.groovy A collection of classes in a script , And traverse // stay ModuleNode The class nodes in are encapsulated in the following members // List<ClassNode> classes = new LinkedList<ClassNode>(); source.AST.classes.find {
// The search name is Student Class // it yes ClassNode node it.name == "Student" }?.methods?.find {
// lookup Student The name under the class is hello Methods // it yes MethodNode node it.name == "hello" }?.with {
// eureka Student Under the hello Method // stay MethodNode Call under the node // it Namely MethodNode node BlockStatement blockStatement = code // Empty BlockStatement Medium List<Statement> statements member // Method intercepts emptying , No longer execute the original method // Method injection does not empty , Will execute the original method content //blockStatement.statements.clear() // Create a method node def methods = new AstBuilder().buildFromSpec {
expression {
methodCall {
variable('this') constant('println') argumentList {
constant('hello buildFromSpec') } } } } // Add the method node to hello In the method //blockStatement.statements.addAll(methods) // Create a method node def methods2 = new AstBuilder().buildFromString('println "hello buildFromString"') // Add the method node to hello In the method //blockStatement.statements.addAll(methods2) // Create a method node , Note that what you get here is def methods3 = new AstBuilder().buildFromCode {
println "hello buildFromCode" } // Add the method node to hello In the method blockStatement.statements.addAll(methods3[0].statements) } }}
3、 Definition Groovy Class and use @Compile Annotations modify the methods that need to be intercepted
Last , Realization Groovy class , Use on the methods of this class @Compile annotation ;
class Student{
def name @Compile def hello(){
println "hello" }}def student = new Student()student.hello()
4、 Execution results
Carry out the above Groovy Script , The execution result is :
hellohello buildFromCode
边栏推荐
- Key structure of ffmpeg - avformatcontext
- Ffmpeg learning - core module
- Model analysis of establishment time and holding time
- Recognize the small experiment of extracting and displaying Mel spectrum (observe the difference between different y_axis and x_axis)
- Classical concurrency problem: the dining problem of philosophers
- 关于slmgr命令的那些事
- [Chongqing Guangdong education] reference materials for Zhengzhou Vocational College of finance, taxation and finance to play around the E-era
- Codeforces Round #804 (Div. 2)【比赛记录】
- [designmode] Decorator Pattern
- Codeforces round 804 (Div. 2) [competition record]
猜你喜欢
AtCoder Beginner Contest 258【比赛记录】
FFT learning notes (I think it is detailed)
FPGA内部硬件结构与代码的关系
Gavin teacher's perception of transformer live class - rasa project actual combat e-commerce retail customer service intelligent business dialogue robot system behavior analysis and project summary (4
数据分析思维分析方法和业务知识——分析方法(二)
剖面测量之提取剖面数据
Problems and solutions of converting date into specified string in date class
时间戳的拓展及应用实例
2022-02-13 work record -- PHP parsing rich text
Leetcode 450 deleting nodes in a binary search tree
随机推荐
Go learning - dependency injection
LeetCode 8. String conversion integer (ATOI)
Go learning --- read INI file
Basic introduction and source code analysis of webrtc threads
Yolov5、Pycharm、Anaconda环境安装
Search (DFS and BFS)
XML配置文件
Spark SQL UDF function
如何利用Flutter框架开发运行小程序
常用API类及异常体系
SQLServer连接数据库读取中文乱码问题解决
STM32 key chattering elimination - entry state machine thinking
看抖音直播Beyond演唱会有感
NLP generation model 2017: Why are those in transformer
DEJA_ Vu3d - cesium feature set 055 - summary description of map service addresses of domestic and foreign manufacturers
[simple implementation of file IO]
小程序技术优势与产业互联网相结合的分析
Cloud guide DNS, knowledge popularization and classroom notes
Opencv classic 100 questions
An understanding of & array names