英文:
Invoke java method from Groovy
问题
我正在研究Groovy,并且尝试在Groovy中绑定Java对象并从脚本中运行方法。
示例:
public class Toaster {
private int toasted = 0;
public Toaster() {
super();
}
public void toast() {
System.out.println(++toasted);
}
}
在Java的主程序中:
Toaster toaster = new Toaster();
Binding binding = new Binding();
binding.setVariable("toaster", toaster);
GroovyShell shell = new GroovyShell(binding);
shell.evaluate("toaster.toast();");
这显然无法正常工作,那么我需要在这里做些什么才能够在Groovy中使用Java的烤面包机对象呢?
英文:
I'm looking into Groovy, and I'm trying to bind java objects in groovy and run methods from the script.
Example:
public class Toaster{
private int toasted=0;
public Toaster() {
super();
}
public void toast(){
System.out.println(++toasted);
}
}
And in the java main I have:
Toaster toaster = new Toaster();
Binding binding = new Binding();
binding.setVariable("toaster", toaster);
GroovyShell shell = new GroovyShell(binding);
shell.evaluate("toaster.toast();");
This obviously doesn't work, so what do I need to do here to be able to use the java toaster object from groovy?
答案1
得分: 2
以下是你提供的代码的翻译部分:
A.java:
import groovy.lang.GroovyShell;
import groovy.lang.Binding;
public class A{
public static class Toaster{
private int toasted=0;
public void toast(){
System.out.println(++toasted);
}
}
public static void main(String[] arg){
Toaster toaster = new Toaster();
Binding binding = new Binding();
binding.setVariable("toaster", toaster);
GroovyShell shell = new GroovyShell(binding);
shell.evaluate("toaster.toast();"); // < prints 1
shell.evaluate("toaster.toast();"); // < prints 2
shell.evaluate("toaster.toast();"); // < prints 3
shell.evaluate("toaster.toast();"); // < prints 4
}
}
编译:
javac -cp %GROOVY_HOME%/lib/* A.java
运行:
java -cp %GROOVY_HOME%/lib/*;. A
英文:
your code works fine if you remove all typos...
A.java:
import groovy.lang.GroovyShell;
import groovy.lang.Binding;
public class A{
public static class Toaster{
private int toasted=0;
public void toast(){
System.out.println(++toasted);
}
}
public static void main(String[] arg){
Toaster toaster = new Toaster();
Binding binding = new Binding();
binding.setVariable("toaster", toaster);
GroovyShell shell = new GroovyShell(binding);
shell.evaluate("toaster.toast();"); // < prints 1
shell.evaluate("toaster.toast();"); // < prints 2
shell.evaluate("toaster.toast();"); // < prints 3
shell.evaluate("toaster.toast();"); // < prints 4
}
}
compile:
javac -cp %GROOVY_HOME%/lib/* A.java
run:
java -cp %GROOVY_HOME%/lib/*;. A
答案2
得分: 0
Groovy和Java将被编译成相同的字节码,保存为.class
文件。因此,您不需要Groovy shell。我不确定您在这里的具体安排。但如果它们需要同时编译,我建议您使用Groovy的编译器groovyc
进行编译,以便它可以识别Java代码的一侧。
英文:
Groovy and java will be compiled to the same bytecode as .class
file. So, you don't need groovy shell. I am not sure what your arrangement here. But if they both need to be compiled at the same time, I suggest you use Groovy's compiler groovyc
to compile, so it can recognize Java side of the code.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论