使用Groovy脚本创建Java类的实例 [英] Create instances of java class using Groovy script

查看:928
本文介绍了使用Groovy脚本创建Java类的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Groovy脚本和Java,我对这个主题很陌生。
我想从groovy脚本创建一个java类(A)的多个实例,并将它们传递给列表,然后将此列表传递给一个新类(B)。

我的B java文件是:

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



<我的一个java文件是:

  public class A {
public long num;

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


我的主要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是:

<$ p $ new $($)$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ my $新A(3))

b.getValues(myList)

I当我运行我的App
异常在线程主groovy.lang.MissingPropertyException:没有这样的属性:A类:文件



当我添加A到java groovy初始化
binding.setVariable(a,new A());

我在列表3中A的对象,但它们都包含num中的值3(可能列表中的所有3个对象都是同一个对象)。



感谢所有我可以获得的帮助解决这个问题。

解决方案

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

  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

这篇关于使用Groovy脚本创建Java类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆