为 Thread
扩展 hello 方法 , 在该方法中传入 Closure
参数 , 在该方法中 , 执行传入的闭包参数 ;
class ThreadExt {
public static Thread hello(Thread self, Closure closure) {
closure()
return self
}
}
在 工程根目录\src\main\groovy\ 目录下创建 manifest\META-INF\services 目录 ,
在 工程根目录\src\main\groovy\manifest\META-INF\services 目录下 , 创建 org.codehaus.groovy.runtime.ExtensionModule 配置文件 , 配置如下内容 :
moduleName=groovyExt
moduleVersion=1.0
extensionClasses=ThreadExt
moduleName 是模块名称 , 可以配置一个任意字符串标识符 ,
moduleVersion 是模块版本 ,
staticExtensionClasses 用于配置 静态扩展方法 , extensionClasses 用于配置 实例扩展方法 ;
这里配置的是 实例扩展方法 ;
配置完成后的项目结构如下 :
在 Terminal 面板中 , 执行
cd src/main/groovy
命令 , 进入到 src/main/groovy 目录中 ,
然后执行
groovyc -d classes ThreadExt.groovy
命令 , 编译 ThreadExt.groovy 源码到 classes 目录中 ; 其中 ThreadExt.groovy 中定义了 Thread 类的扩展方法 ;
编译过程及结果如下 :
在 执行
jar -cf thread.jar -C classes . -C manifest/ .
命令 , 将 classes 中的字节码文件按照 manifest/ 规则 , 打包到 thread.jar 文件中 ;
创建一个 Groovy 脚本 , 执行为 Thread 扩展的静态方法 hello 方法 ;
new Thread().hello{
printf "Hello"
}
在 Terminal 面临中 , 使用命令行执行该 Groovy 脚本 ,
groovy -classpath thread.jar ThreadExtApplication.groovy
执行结果为 :
Hello
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有