javagroovygroovyscriptengine

Create instances of java class using Groovy script


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.


Solution

  • 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