POM
<!-- https://mvnrepository.com/artifact/org.codehaus.groovy/groovy-all --><dependency> <groupId>org.codehaus.groovy</groupId> <artifactId>groovy-all</artifactId> <version>2.4.7</version></dependency><!-- https://mvnrepository.com/artifact/org.codehaus.groovy/groovy --><dependency> <groupId>org.codehaus.groovy</groupId> <artifactId>groovy</artifactId> <version>2.4.7</version></dependency><dependency> <groupId>org.kohsuke</groupId> <artifactId>groovy-sandbox</artifactId> <version>1.6</version></dependency>
Java
public class GroovyTest { /** * 语法校验 */ @Test public void grammarCheck() { try { String expression = "if(a==1) return 1;"; new GroovyShell().parse(expression); } catch(MultipleCompilationErrorsException cfe) { ErrorCollector errorCollector = cfe.getErrorCollector(); System.out.println("Errors: "+errorCollector.getErrorCount()); } } class NoSystemExitSandbox extends GroovyInterceptor { @Override public Object onStaticCall(GroovyInterceptor.Invoker invoker, Class receiver, String method, Object... args) throws Throwable { if (receiver==System.class && method=="exit") throw new SecurityException("No call on System.exit() please"); return super.onStaticCall(invoker, receiver, method, args); } } class NoRunTimeSandbox extends GroovyInterceptor { @Override public Object onStaticCall(GroovyInterceptor.Invoker invoker, Class receiver, String method, Object... args) throws Throwable { if (receiver==Runtime.class) throw new SecurityException("No call on RunTime please"); return super.onStaticCall(invoker, receiver, method, args); } } /** * 沙盒运行 */ @Test public void sandboxRun() { final GroovyShell sh = new GroovyShell(new CompilerConfiguration() .addCompilationCustomizers(new SandboxTransformer())); new NoSystemExitSandbox().register(); new NoRunTimeSandbox().register(); sh.evaluate("System.exit(0)"); }}