1、groovyshell 脚本语言运用,支持表达式及脚本文件:
def run(foo) {
println 'Hello World!'
x = 123
foo * 10
}
run foo
public class Testgroovyshell {
/**
* @param args
*/
public static void main(String[] args) {
try {
Binding binding = new Binding();
binding.setProperty("foo",new Integer(2));
groovyshell shell = new groovyshell(binding);
Object value = shell.evaluate(new File("src/groovy/groovyshellHellow.groovy"));
System.out.println(value);
} catch (CompilationFailedException e) {
e.printstacktrace();
} catch (IOException e) {
e.printstacktrace();
}
}
}
2、在Java中动态加载和运行Groovy代码
package groovy;
/**
* @author zhangchao02
*
*/
public class talk{
public String say(String talkContext) {
System.out.println("my say:" + talkContext);
return talkContext;
}
}
public class Testgroovyshell {
/**
* @param args
*/
public static void main(String[] args) {
try {
Binding binding = new Binding();
binding.setProperty("foo",new Integer(2));
groovyshell shell = new groovyshell(binding);
Object value = shell.evaluate(new File("src/groovy/groovyshellHellow.groovy"));
System.out.println(value);
} catch (CompilationFailedException e) {
e.printstacktrace();
} catch (IOException e) {
e.printstacktrace();
}
}
}
public class GroovyHelper {
private static final Logger logger = LoggerFactory.getLogger(GroovyHelper.class);
private static GroovyClassLoader loader;
static {
ClassLoader cl = new GroovyHelper().getClass()
.getClassLoader();
loader = new GroovyClassLoader(cl);
}
private GroovyHelper() {
};
public static GroovyObject getGroovyObject(String filePath) {
File groovyFile = new File(filePath);
if(!groovyFile.exists()){
logger.error("GroovyHelper getGroovyObject groovyFile is not exists filePath={}",filePath);
return null;
}
GroovyObject groovyObject = null;
try {
loader.parseClass(groovyFile);
Class<?> groovyClass = loader.parseClass(groovyFile);
groovyObject = (GroovyObject) groovyClass.newInstance();
} catch (Exception e) {
e.printstacktrace();
}
return groovyObject;
}
public static Object invokeMethod(GroovyObject groovyObject,
String paramString,Object paramObject) {
Object result = groovyObject.invokeMethod(paramString,paramObject);
return result;
}
public static Object invokeMethodShell(){
Object result = null;
return result;
}
}
3、groovy 脚本引擎:
public static void main(String[] args) { String[] roots = new String[] {"src/groovy/"} ; try { GroovyScriptEngine gse = new GroovyScriptEngine(roots); Binding binding = new Binding(); binding.setProperty("foo",new Integer(2)); gse.run( "groovyshellHellow.groovy",binding); System.out.println(binding.getvariable("x")); System.out.println(binding.getvariable("foo")); } catch (IOException e) { // Todo Auto-generated catch block e.printstacktrace(); } catch (ResourceException e) { // Todo Auto-generated catch block e.printstacktrace(); } catch (ScriptException e) { // Todo Auto-generated catch block e.printstacktrace(); } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。