[英]groovy closure for complex object
如何為下面的復雜場景編寫閉包
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詳細信息? 任何提示想法?
我不確定你是什么意思...
要遍歷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),而不是通過實現BuilderSupport
來提出類似於MarkupBuilder
的東西可能更好
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.