Create instances of java class using Groovy script

為{幸葍}努か 提交于 2020-01-05 08:26:15

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/45082379/create-instances-of-java-class-using-groovy-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!