且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-12-05 15:01:04

现在我测试了它,让我们把它写下来作为答案:

  import path.to.my.classes.A; //这是必需的

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

b.setValues(myList)

还有其他的方法可以做到这一点,例如自动导入,您可以使用绑定(iirc)传递,但是无论如何编写导入都会更好(imo),因为主程序可能不知道脚本会执行什么操作。

tl:dr



我只想要rep:D


I am using Groovy script and Java, I am new to the subject. 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).

my B java file is:

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

my A java file is:

public class A {
 public long num;

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

my main java files is:

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:

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

when I am adding A to the java groovy initialize 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).

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.

tl:dr

I just want the rep :D