如何检查 groovy 脚本的编译错误

How to check groovy script for compilation errors

我们可以使用下面的代码运行在运行时创建和运行 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())

现在假设在上面的代码中,我们引入了一个错误,现在上面的代码如下:

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())

注意,我们在 class 声明后的脚本中添加了 "jajaja"。

在这里应该做什么才能知道我们的脚本有编译错误并且会因 MissingPropertyException 或其他异常而失败。

当尝试使用 groovyConsole 时,它​​会中断脚本并出现以下错误

1 compilation error:

unexpected token: jajaja at line: 1, column: 15

我们可以在 运行 之前测试脚本是否存在任何编译错误吗? 对于此代码,添加 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
        }

虽然一个后备方案是,只要您有部分脚本代码,其余代码将在以后从其他脚本中添加。此代码将失败,但这是开发人员问题而不是技术问题。

此外,这将 运行 可能导致数据更新的脚本很糟糕。