如何为以下复杂场景编写闭包
def empList=[];
EmployeeData empData = null;
empData=new EmployeeDataImpl("anish","nath");
empList.add(empData );
empData=new EmployeeDataImpl("JOHN","SMITH");
empList.add(empData );
Employee employee= new Employee(empList);
如何编写闭包以便使用emplyee对象我将获得empData详细信息?任何提示想法?
答案 0 :(得分:2)
我不确定你的意思......
要迭代EmployeeData
,您只需使用each
:
empList.each { println it }
要查找特定条目,您可以使用find
:
// Assume EmployeeData has a firstName property, you don't show its structure
EmployeeData anish = empList.find { it.firstName == 'anish' }
或者您可以使用findAll
def smiths = empList.findAll { it.surname == 'Smith' }
这取决于你想要的“关闭”......
是的,在你解释了你想要的DSL之后,我想出了这个(这将解决给定的问题):
@groovy.transform.Canonical
class EmployeeData {
String firstName
String lastName
}
class Employee {
List<EmployeeData> empList = []
Employee( List<EmployeeData> list ) {
empList = list
}
}
class EmployeeDSL {
Employee root
List propchain = []
EmployeeDSL( Employee root ) {
this.root = root
}
def propertyMissing( String name ) {
// if name is 'add' and we have a chain of names
if( name == 'add' && propchain ) {
// add a new employee
root.empList << new EmployeeData( firstName:propchain.take( 1 ).join( ' ' ), lastName:propchain.drop( 1 ).join( ' ' ) )
// and reset the chain of names
propchain = []
}
else {
// add this name to the chain of names
propchain << name
this
}
}
}
Employee emp = new Employee( [] )
new EmployeeDSL( emp ).with {
anish.nath.add
tim.yates.add
}
emp.empList.each {
println it
}
它使用take()
和drop()
,所以你需要groovy 1.8.1 +
希望它有意义!然而,这是一个奇怪的语法(使用关键字add
将字符串添加为Employee),而不是通过实现{{MarkupBuilder
来提出类似BuilderSupport
的内容可能更好。 1}}