使用Groovy 2.0
GPath属性表达式是否可以使用谓词进行过滤:
class HandShaker {
String title
}
class AussieGreeter implements Greeter {
String name
List<HandShaker> handshaker
....
}
AussieGreeter greeter = new AussieGreeter()
greeter.setName("hello")
greeter.setHandshaker([new Handshaker().setTitle("butler")].asList()])
println Eval.x(greeter,"x[name=='hello'].handshaker[0].title")
如果name属性等于“hello”,要过滤Greeter?没有看到像这样的例子和Groovy使用MissingPropertyException保释。
答案 0 :(得分:1)
我认为你需要这样做:
println Eval.x(greeter,"x.find { it.name == 'hello' }.handshaker[0].title")
你可以破解getAt
的{{1}}方法进行关闭,如果返回AussieGreeter
或true
,则返回该元素,否则如下:
null
哪个更接近您的原始要求(但在比较时有大括号,在方括号后有class HandShaker {
String title
}
interface Greeter {}
class AussieGreeter implements Greeter {
String name
List<HandShaker> handshaker
def getAt( Closure o ) {
o.delegate = this
o.resolveStrategy = Closure.DELEGATE_FIRST
o() ? this : null
}
}
AussieGreeter greeter = new AussieGreeter( name:'hello',
handshaker:[new HandShaker( title:'butler' )] )
greeter[ { name == 'hello' } ]?.handshaker[0].title
)
但是?
更容易阅读imho: - /