【Groovy】编译时元编程 ( ASTTransformation#visit 方法获取 Groovy 源文件 )
文章目錄
- 一、ASTTransformation#visit 方法獲取 Groovy 源文件
- 二、完整代碼示例
- 1、Groovy 腳本 Groovy.groovy
- 2、ASTTransformation 接口實現 MyASTTransformation.groovy
- 3、配置 ASTTransformation
- 3、使用命令行進行編譯時處理
一、ASTTransformation#visit 方法獲取 Groovy 源文件
在 ASTTransformation#visit 方法中 , 使用 source.AST 也可以獲取 AST 語法樹根節點 , 使用 source.source.reader.text 可以和獲取 Groovy 類源碼的字符串形式 ;
- AST 語法樹根節點 ASTNode[] nodes :
- 源碼 SourceUnit source :
- 使用 source.AST 獲取 AST 語法樹根節點 :
- 使用 source.source.reader.text 獲取源碼內容 :
也就是說在 ASTTransformation 中的 visit 方法中 , 可以拿到任何 Groovy 腳本 , Groovy 類 , Groovy 方法 , 字段 , 屬性 相關的數據 ;
二、完整代碼示例
1、Groovy 腳本 Groovy.groovy
class Student{def namedef hello(){println "hello"} }def student = new Student()
2、ASTTransformation 接口實現 MyASTTransformation.groovy
import org.codehaus.groovy.ast.ASTNode import org.codehaus.groovy.control.SourceUnit import org.codehaus.groovy.transform.ASTTransformation import org.codehaus.groovy.transform.GroovyASTTransformation@GroovyASTTransformation class MyASTTransformation implements ASTTransformation {/*** 編譯時處理方法* @param nodes AST 抽象語法樹節點 , 是 ASTNode 數組類型* @param source 源單元 , 可以通過該對象拿到源文件*/@Overridevoid visit(ASTNode[] nodes, SourceUnit source) {println nodesprintln sourceprintln source.ASTprintln source.source.reader.text} }
3、配置 ASTTransformation
創建 Y:\002_WorkSpace\003_IDEA\Groovy_Demo2\src\main\groovy\resources\META-INF\services\org.codehaus.groovy.transform.ASTTransformation 目錄層級及文件 , 在文件中配置 ASTTransformation 實現類的全類名 :
MyASTTransformation3、使用命令行進行編譯時處理
首先 , 進入 Y:\002_WorkSpace\003_IDEA\Groovy_Demo2\src\main\groovy 目錄 ,
cd Y:\002_WorkSpace\003_IDEA\Groovy_Demo2\src\main\groovy然后 , 編譯 編譯時處理類 MyASTTransformation.groovy , 將編譯后的字節碼文件 MyASTTransformation.class 保存到 Y:\002_WorkSpace\003_IDEA\Groovy_Demo2\src\main\groovy\classes 目錄下 ,
groovyc -d classes MyASTTransformation.groovy再后 , 打包上述編譯好的字節碼文件 , 存放在 Y:\002_WorkSpace\003_IDEA\Groovy_Demo2\src\main\groovy\test.jar 路徑 ;
jar -cf test.jar -C classes . -C resources .最后 , 依賴 test.jar 執行 Groovy.groovy 腳本
groovy -classpath test.jar Groovy.groovy執行結果為 :
[org.codehaus.groovy.ast.ModuleNode@2609b277] org.codehaus.groovy.control.SourceUnit@1fd14d74 org.codehaus.groovy.ast.ModuleNode@2609b277 class Student{def namedef hello(){println "hello"} }def student = new Student()總結
以上是生活随笔為你收集整理的【Groovy】编译时元编程 ( ASTTransformation#visit 方法获取 Groovy 源文件 )的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Groovy】编译时元编程 ( AST
- 下一篇: 【Groovy】编译时元编程 ( AST