从 Java 调用 Groovy 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3989592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calling a Groovy function from Java
提问by joemoe
How do you call a function defined in a Groovy script file from Java?
如何从 Java 调用 Groovy 脚本文件中定义的函数?
Example groovy script:
示例 groovy 脚本:
def hello_world() {
println "Hello, world!"
}
I've looked at the GroovyShell, GroovyClassLoader, and GroovyScriptEngine.
我看过 GroovyShell、GroovyClassLoader 和 GroovyScriptEngine。
回答by toolkit
Either
任何一个
- Compile as ataylor suggests
- Use JSR-223 as explained here
- If you are using Spring, have a groovy class that implements a Java interface, and inject into your code with:
<lang:groovy id="messenger" script-source="classpath:Messenger.groovy">
<lang:property name="message" value="I Can Do The Frug" />
</lang:groovy>
One advantage of the spring approach is the concept of 'refreshable beans'. That is, Spring can be configured to monitor your script file for modifications, and replace at runtime.
spring 方法的一个优点是“可刷新豆”的概念。也就是说,Spring 可以配置为监视您的脚本文件的修改,并在运行时替换。
回答by ataylor
The simplest way is to compile the script into a java class file and just call it directly. Example:
最简单的方法是将脚本编译成java类文件,直接调用即可。例子:
// Script.groovy
def hello_world() {
println "Hello, World!"
}
// Main.java
public class Main {
public static void main(String[] args) {
Script script = new Script();
script.hello_world();
}
}
$ groovyc Script.groovy
$ javac -classpath .:$GROOVY_HOME/embeddable/groovy-all-1.7.5.jar Main.java
$ java -classpath .:$GROOVY_HOME/embeddable/groovy-all-1.7.5.jar Main
Hello, World!
回答by tim_yates
Assuming you have a file called test.groovy
, which contains (as in your example):
假设您有一个名为 的文件test.groovy
,其中包含(如您的示例):
def hello_world() {
println "Hello, world!"
}
Then you can create a file Runner.java
like this:
然后你可以创建一个Runner.java
这样的文件:
import groovy.lang.GroovyShell ;
import groovy.lang.GroovyClassLoader ;
import groovy.util.GroovyScriptEngine ;
import java.io.File ;
class Runner {
static void runWithGroovyShell() throws Exception {
new GroovyShell().parse( new File( "test.groovy" ) ).invokeMethod( "hello_world", null ) ;
}
static void runWithGroovyClassLoader() throws Exception {
// Declaring a class to conform to a java interface class would get rid of
// a lot of the reflection here
Class scriptClass = new GroovyClassLoader().parseClass( new File( "test.groovy" ) ) ;
Object scriptInstance = scriptClass.newInstance() ;
scriptClass.getDeclaredMethod( "hello_world", new Class[] {} ).invoke( scriptInstance, new Object[] {} ) ;
}
static void runWithGroovyScriptEngine() throws Exception {
// Declaring a class to conform to a java interface class would get rid of
// a lot of the reflection here
Class scriptClass = new GroovyScriptEngine( "." ).loadScriptByName( "test.groovy" ) ;
Object scriptInstance = scriptClass.newInstance() ;
scriptClass.getDeclaredMethod( "hello_world", new Class[] {} ).invoke( scriptInstance, new Object[] {} ) ;
}
public static void main( String[] args ) throws Exception {
runWithGroovyShell() ;
runWithGroovyClassLoader() ;
runWithGroovyScriptEngine() ;
}
}
compile it with:
编译它:
$ javac -cp groovy-all-1.7.5.jar Runner.java
Note: Runner.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
(Note: The warnings are left as an exercise to the reader) ;-)
(注意:警告留给读者作为练习);-)
Then, you can run this Runner.class with:
然后,您可以使用以下命令运行此 Runner.class:
$ java -cp .:groovy-all-1.7.5.jar Runner
Hello, world!
Hello, world!
Hello, world!
回答by raulsaeztapia
You too can use the Bean Scripting Frameworkto embed any scripting language into your Java code. BSF give you the opportunity of integrate other languages, but is not native integration.
您也可以使用Bean Scripting Framework将任何脚本语言嵌入到您的 Java 代码中。BSF 为您提供了集成其他语言的机会,但不是本地集成。
If you are clearly focused to use Groovy the GroovyScriptEngine is the most complete solution.
如果您显然专注于使用 Groovy,那么 GroovyScriptEngine 是最完整的解决方案。
=)
=)
回答by Alfredo Diaz
One simple example:
一个简单的例子:
import groovy.lang.GroovyClassLoader;
import groovy.lang.Script;
public class GroovyEmbedder {
static public final String GROOVY_SCRIPT=
"println ('Hello World !')";
static public void main(String[] args) throws Exception {
((Script) new GroovyClassLoader().parseClass(GROOVY_SCRIPT).newInstance()).run();
}
}
Testing
测试
> javac -cp groovy-all-2.4.10.jar GroovyEmbedder.java
> java -cp groovy-all-2.4.10.jar:. GroovyEmbedder
Hello World !
回答by Eugene Lopatkin
Just more elegant ways:
只是更优雅的方式:
GroovyScriptEngine engine = new GroovyScriptEngine( "." )
Object instance = engine
.loadScriptByName(scriptName)
.newInstance()
Object result = InvokerHelper.invokeMethod(instance, methodName, args)
And if script class extends groovy.lang.Script
:
如果脚本类扩展groovy.lang.Script
:
Object result = engine
.createScript(scriptName, new Binding())
.invokeMethod(methodName, args)
No need to extend groovy.lang.Script
if you just want call main
method of your groovy class:
groovy.lang.Script
如果您只想调用main
groovy 类的方法,则无需扩展:
Object result = engine
.createScript(scriptName, new Binding())
.run()