|
2019-05-17
package com.funtest.groovytest import com.funtester.frame.SourceCode class HotUpdate extends SourceCode { public static void main(String[] args) { def update = new HotUpdate() update.test() HotUpdate.metaClass.test = {output("FunTester")} def update2 = new HotUpdate() update2.test() } public void test() { output(123) } }
控制台输出:
INFO-> main 当前用户:oker,工作目录:/Users/oker/IdeaProjects/funtester/,系统编码格式:UTF-8,系统Mac OS X版本:10.16 INFO-> main ###### # # # # ####### ###### ##### ####### ###### ##### # # # ## # # # # # # # # # # # # # # # # # # # # # # #### # # # # # # #### ##### # #### ##### # # # # # # # # # # # # # # # # # ## # # # # # # # # # ##### # # # ###### ##### # ###### # # INFO-> main 123 INFO-> main FunTester Process finished with exit code 0
经过功能验证,路已经通了。现在就开始编写脚本,脚本内容就是把metaClass重新实现test()方法的功能脚本化:
import com.funtest.groovytest.HotUpdate import com.funtester.frame.Output HotUpdate.metaClass.test = {Output.output(\"FunTester\")}
接下来,我通过groovy.lang.GroovyShell
模拟服务器收到请求脚本(String类型参数)之后的功能。最后完整的代码就是:
import com.funtester.frame.SourceCode import com.funtester.frame.execute.ExecuteGroovy class HotUpdate extends SourceCode { public static void main(String[] args) { def update = new HotUpdate() update.test() ExecuteGroovy.executeScript("import com.funtest.groovytest.HotUpdate\n" + "import com.funtester.frame.Output \n" + "\n" + "HotUpdate.metaClass.test = {Output.output(\"FunTester\")}") def update2 = new HotUpdate() update2.test() } public void test() { output(123) } }
控制台输出:
INFO-> main 当前用户:oker,工作目录:/Users/oker/IdeaProjects/funtester/,系统编码格式:UTF-8,系统Mac OS X版本:10.16 INFO-> main ###### # # # # ####### ###### ##### ####### ###### ##### # # # ## # # # # # # # # # # # # # # # # # # # # # # #### # # # # # # #### ##### # #### ##### # # # # # # # # # # # # # # # # # ## # # # # # # # # # ##### # # # ###### ##### # ###### # # INFO-> main 123 INFO-> main FunTester Process finished with exit code 0
完美实现,中间在拷贝脚本的时候遇到一些问题,就是Intellij会自动把一些字符当做转义字符来处理,导致执行的脚本和实际脚本有了差异导致失败,这里建议大家尽量避免使用这种直接粘贴复制字符串的方式,转而使用上传脚本文件或者使用ngrinder的方案,将脚本存放在可访问的Git仓库中。
编辑:航网科技 来源:腾讯云 本文版权归原作者所有 转载请注明出处
微信扫一扫咨询客服
全国免费服务热线
0755-36300002