Vin*_*ati 6 grails groovy grails-plugin grails-2.0
我们可以使用下面的代码在运行时创建和运行 groovyscript
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
import java.io.File;
import java.io.IOException;
// Create a String with Groovy code.
final StringBuilder groovyScript = new StringBuilder();
groovyScript.append("class Sample {");
groovyScript.append(" String sayIt() { return \"Groovy says: Cool jajaja\" }");
groovyScript.append("}");
GroovyClassLoader gcl = new GroovyClassLoader()
GroovyCodeSource codeSource = new GroovyCodeSource(groovyScript.toString(), "aa", GroovyShell.DEFAULT_CODE_BASE)
//GCL will check for enabled cache over code source and use sourceCache to cache code with name
def scriptClass = gcl.parseClass(codeSource)
def classInstance = scriptClass.newInstance()
assert "Groovy says: Cool jajaja".equals(classInstance.sayIt())
Run Code Online (Sandbox Code Playgroud)
现在假设在上面的代码中,我们引入了一个错误,现在上面的代码如下:
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
import java.io.File;
import java.io.IOException;
// Create a String with Groovy code.
final StringBuilder groovyScript = new StringBuilder();
groovyScript.append("class Sample {");
groovyScript.append("jajaja");
groovyScript.append(" String sayIt() { return \"Groovy says: Cool jajaja\" }");
groovyScript.append("}");
GroovyClassLoader gcl = new GroovyClassLoader()
GroovyCodeSource codeSource = new GroovyCodeSource(groovyScript.toString(), "aa", GroovyShell.DEFAULT_CODE_BASE)
//GCL will check for enabled cache over code source and use sourceCache to cache code with name
def scriptClass = gcl.parseClass(codeSource)
def classInstance = scriptClass.newInstance()
assert "Groovy says: Cool jajaja".equals(classInstance.sayIt())
Run Code Online (Sandbox Code Playgroud)
请注意,我们在类声明后的脚本中添加了“jajaja”。
在这里应该做什么才能知道我们的脚本有编译错误并且会因 MissingPropertyException 或其他异常而失败。
使用 groovyConsole 尝试相同时,它会因以下错误而破坏脚本
1 compilation error:
unexpected token: jajaja at line: 1, column: 15
Run Code Online (Sandbox Code Playgroud)
我们可以在运行之前测试脚本是否有任何编译错误吗?对于此代码,添加 try catch 块对我不起作用。
GroovyShell 通过使用 try-catch 块可以很好地工作。
GroovyCodeSource codeSource = new GroovyCodeSource(script, "aa", GroovyShell.DEFAULT_CODE_BASE)
//GCL will check for enabled cache over code source and use sourceCache to cache code with name
def scriptClass
try {
def shell = new GroovyShell()
def data = shell.parse(codeSource.scriptText)
data.run()
}catch (Throwable e){
status = false
}
if(!status){
return "domain.script.compilation.errors"
}else{
return true
}
Run Code Online (Sandbox Code Playgroud)
尽管一个后备方案是,每当您有一个不完整的脚本代码时,其余的代码都会稍后从其他脚本添加。这段代码将会失败,但这是开发人员的问题,而不是技术问题。
此外,这将运行脚本,这可能会导致数据更新,这是不好的。