考虑一种方法
def public Set<AgeRange> getAgeRanges(boolean excludeSenior) {
-- something ---
}
如何为此编写 ExpandoMetaClass
ClassName.metaClass.methodName << { boolean excludeSenior->
-- something ---
}
考虑一种方法
def public Set<AgeRange> getAgeRanges(boolean excludeSenior) {
-- something ---
}
如何为此编写 ExpandoMetaClass
ClassName.metaClass.methodName << { boolean excludeSenior->
-- something ---
}
我不太确定你在问什么,但这可能表明你在寻找什么:
一些类:
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]
这有帮助吗?
我在 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