考虑一种方法
def public Set<AgeRange> getAgeRanges(boolean excludeSenior) {
-- something ---
}
如何为此编写ExpandoMetaClass
ClassName.metaClass.methodName << { boolean excludeSenior->
-- something ---
}
答案 0 :(得分:1)
我在Groovy控制台中试过这个并且它有效:
class Something {
Set getAgeRanges(boolean excludeSenior) {
[1, 2, 3] as Set
}
}
// test the original method
def s = new Something()
assert s.getAgeRanges(true) == [1, 2, 3] as Set
// replace the method
Something.metaClass.getAgeRanges = { boolean excludeSenior ->
[4, 5, 6] as Set
}
// test the replacement method
s = new Something()
assert s.getAgeRanges(true) == [4, 5, 6] as Set
答案 1 :(得分:1)
我不确定你在问什么,但这可能证明你在寻找什么:
某些课程:
class SomeClass {
List<Integer> ages
}
为类添加方法的一些元编程:
SomeClass.metaClass.agesOlderThan { int minimumAge ->
// note that "delegate" here will be the instance
// of SomeClass which the agesOlderThan method
// was invoked on...
delegate.ages?.findAll { it > minimumAge }
}
创建SomeClass的实例并调用新方法...
def sc = new SomeClass(ages: [2, 12, 22, 32])
assert sc.agesOlderThan(20) == [22, 32]
这有帮助吗?