import groovy.lang.Binding;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
import groovy.lang.GroovyShell;
import groovy.util.ResourceException;
import groovy.util.ScriptException;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import org.codehaus.groovy.control.CompilationFailedException;
public class Test {
public static void main(String[] args) throws CompilationFailedException,
IOException, InstantiationException, IllegalAccessException,
ResourceException, ScriptException, IllegalArgumentException,
SecurityException, InvocationTargetException, NoSuchMethodException {
GroovyShell shell = new GroovyShell(new Binding());
Object b = shell
.evaluate("import com.talents.compiler.groovy.math.AlgorithmBridge; AlgorithmBridge.max('11 1')");
System.out.println("fun " + b.toString());
}
public static void fun3(String path) throws IOException, ResourceException,
ScriptException, InstantiationException, IllegalAccessException,
IllegalArgumentException, SecurityException,
InvocationTargetException, NoSuchMethodException {
String scriptText = "class Foo {\n"
+ " int add(int x, int y) { x + y }}";
GroovyClassLoader loader = new GroovyClassLoader();
Class<?> newClazz = loader.parseClass(scriptText);
Object obj = newClazz.newInstance();
Object i = obj.getClass().getMethod("add", int.class, int.class)
.invoke(obj, 2, 3);
System.out.println(i);
}
public static void fun2(String path) {
String scriptText = " if(values){ 1;}else{ 2}";
Binding binding = new Binding();
binding.setVariable("values", 10);
GroovyShell shell = new GroovyShell(binding);
Object b = shell.evaluate(scriptText);
System.out.println("fun " + b.toString());
}
@SuppressWarnings("rawtypes")
public static void fun1(String path) throws Exception, IOException {
ClassLoader parent = RunScriptService.class.getClassLoader();
GroovyClassLoader loader = new GroovyClassLoader(parent);
Class groovyClass = loader.parseClass(new File(path));
GroovyObject groovyObject = (GroovyObject) groovyClass.newInstance();
System.out.println(groovyObject.invokeMethod("sum", "1 1 1 "));
}
}
Java动态加载Groovy脚本
最新推荐文章于 2024-02-20 12:10:35 发布