我正在使用 ObjectGraphBuilder 来构建一个复杂的对象。有没有办法基于现有的 java 对象而不是 groovy 对象来构建它?谢谢
更新 8/16:这是不起作用的代码,以及我得到的异常。唯一的 groovy 代码是 MyMain.groovy。其他一切都是java。
public class Company {
private String name;
private Address address;
private List<Employee> employees;
//getters and setters
}
public class Employee {
private String name;
private int employeeId;
//getters and setters
}
public class Address {
private String line1;
private String line2;
private int zip;
private String state;
//getters and setters
}
class MyMain {
def company
Company createCompany() {
def builder = new ObjectGraphBuilder()
company = builder.company(name: 'ACME'){
address(line1: '32 fifth st', line2: 'apt 423')
3.times {
employee(employeeId: 20, name: 'joe smith')
}
}
}
}
public class Blah {
public static void main(String[] args) {
MyMain myMain = new MyMain();
Company c = myMain.createCompany();
System.out.println(c.getName());
System.out.println(c.getAddress().getLine1());
System.out.println(c.getAddress().getLine2());
System.out.println("tot # of employees " + c.getEmployees().size());
}
}
Exception in thread "main" org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'Employee@152441a' with class 'Employee' to class 'java.util.List'
at org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.castToType(DefaultTypeTransformation.java:360)
at groovy.lang.MetaClassImpl.setProperty(MetaClassImpl.java:2465)
at groovy.lang.MetaClassImpl.setProperty(MetaClassImpl.java:3412)
at org.codehaus.groovy.runtime.InvokerHelper.setProperty(InvokerHelper.java:196)
更新 2
原来你必须初始化列表。所以,如果你把
private List<Employee> employees = new ArrayList<Employee>();
然后,它会工作。但是对于数组呢?我尝试创建一个空数组,但这不起作用。它会毫无例外地运行,但无论我的构建器中有多少员工语句,数组的大小都只会是 1。
employee(employeeId: 20, name: 'joe smith')
employee(employeeId: 10, name: 'geno smith')
employee(employeeId: 80, name: 'your mom')
我注意到,如果您遍历数组,无论您在构建器中指定的最后一个员工是什么,最终都会成为数组中的那个。