简体   繁体   English

使用Groovy脚本创建Java类的实例

[英]Create instances of java class using Groovy script

I am using Groovy script and Java, I am new to the subject. 我正在使用Groovy脚本和Java,我是这个主题的新手。 I am trying to create multiple instances of a java class (A) from groovy script and pass them to list, then pass this list to a new class (B). 我试图从groovy脚本中创建一个Java类(A)的多个实例,并将它们传递给列表,然后将此列表传递给新的类(B)。

my B java file is: 我的B java文件是:

public class B {
 public void getValues(List<A> values) {...}
}

my A java file is: 我的Java文件是:

public class A {
 public long num;

 public A(long num){
  this.num = num;
 }
}

my main java files is: 我的主要Java文件是:

GroovyScriptEngine groovyScriptEngine = new GroovyScriptEngine(/*path to     file.groovy*/);
Binding binding = new Binding();
binding.setVariable("b", new B());
groovyScriptEngine.run("file.groovy", binding);

my file.groovy is: 我的file.groovy是:

def myList = []
myList.add(new A(1))
myList.add(new A(2))
myList.add(new A(3))

b.getValues(myList)

I keep getting this exception when I am running my App Exception in thread "main" groovy.lang.MissingPropertyException: No such property: A for class: file 当我在线程“ main” groovy.lang.MissingPropertyException中运行我的应用程序异常时,我不断收到此异常:无此类属性:类:文件的A

when I am adding A to the java groovy initialize binding.setVariable("a", new A()); 当我在Java groovy中添加A时,请初始化binding.setVariable(“ a”,new A());

I am getting in the list 3 objects of A but all of them contain the value 3 in the num (probably all 3 objects in the list are the same object). 我进入A的列表3个对象,但它们全部在num中包含值3(列表中的所有3个对象可能都是同一对象)。

appreciate all the help I can get to solve this problem. 感谢您为解决该问题而提供的所有帮助。

Now that I tested it, lets write it down as answer: 现在,我对其进行了测试,让我们将其写下来作为答案:

import path.to.my.classes.A; // this is required

def myList = []
myList.add(new A(1))
myList.add(new A(2))
myList.add(new A(3))

b.setValues(myList)

There are other ways to do it such as automatic imports that you can pass on with the binding (iirc), but it is better (imo) to write the imports anyway as the main program probably doesnt know what the script will do. 还有其他方法可以执行此操作,例如可以通过绑定(iirc)进行自动导入,但是无论如何都最好编写(imo)导入,因为主程序可能不知道脚本会做什么。

tl:dr tl:dr

I just want the rep :D 我只想要代表:D

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM