当前位置:网站首页>[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
边栏推荐
- Idea远程提交spark任务到yarn集群
- STM32 configuration after chip replacement and possible errors
- NLP text processing: lemma [English] [put the deformation of various types of words into one form] [wet- > go; are- > be]
- JS can really prohibit constant modification this time!
- FPGA内部硬件结构与代码的关系
- Anconda download + add Tsinghua +tensorflow installation +no module named 'tensorflow' +kernelrestart: restart failed, kernel restart failed
- Yolov5、Pycharm、Anaconda环境安装
- 电机的简介
- MySql——CRUD
- FFmpeg抓取RTSP图像进行图像分析
猜你喜欢

Problems and solutions of converting date into specified string in date class

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

notepad++正则表达式替换字符串

State mode design procedure: Heroes in the game can rest, defend, attack normally and attack skills according to different physical strength values.

XML配置文件

How to solve the problems caused by the import process of ecology9.0

AtCoder Beginner Contest 254【VP记录】

Search (DFS and BFS)

时间戳的拓展及应用实例

Gd32f4xx UIP protocol stack migration record
随机推荐
如何利用Flutter框架开发运行小程序
Data analysis thinking analysis methods and business knowledge -- analysis methods (II)
Global and Chinese market of valve institutions 2022-2028: Research Report on technology, participants, trends, market size and share
[Chongqing Guangdong education] Chongqing Engineering Vocational and Technical College
【线上小工具】开发过程中会用到的线上小工具合集
建立时间和保持时间的模型分析
Determinant learning notes (I)
NLP basic task word segmentation third party Library: ICTCLAS [the third party library with the highest accuracy of Chinese word segmentation] [Chinese Academy of Sciences] [charge]
Pointer - character pointer
Calculate sha256 value of data or file based on crypto++
Knowledge about the memory size occupied by the structure
LeetCode 6006. Take out the least number of magic beans
MySql——CRUD
Global and Chinese markets for hinged watertight doors 2022-2028: Research Report on technology, participants, trends, market size and share
孤勇者
Key structure of ffmpeg - avformatcontext
Atcoder beginer contest 258 [competition record]
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
Codeforces round 804 (Div. 2) [competition record]
小程序技术优势与产业互联网相结合的分析