从 Java 调用 Groovy 函数 [英] Calling a Groovy function from Java
本文介绍了从 Java 调用 Groovy 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从 Java 调用 Groovy 脚本文件中定义的函数?
How do you call a function defined in a Groovy script file from Java?
示例 groovy 脚本:
Example groovy script:
def hello_world() {
println "Hello, world!"
}
我查看了 GroovyShell、GroovyClassLoader 和 GroovyScriptEngine.
I've looked at the GroovyShell, GroovyClassLoader, and GroovyScriptEngine.
推荐答案
假设您有一个名为 test.groovy
的文件,其中包含(如您的示例):
Assuming you have a file called test.groovy
, which contains (as in your example):
def hello_world() {
println "Hello, world!"
}
然后你可以像这样创建一个文件Runner.java
:
Then you can create a file Runner.java
like this:
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() ;
}
}
编译:
$ 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) ;-)
然后,您可以使用以下命令运行此 Runner.class:
Then, you can run this Runner.class with:
$ java -cp .:groovy-all-1.7.5.jar Runner
Hello, world!
Hello, world!
Hello, world!
这篇关于从 Java 调用 Groovy 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文