Har*_*cle 1 generics groovy delegates default
我有一个封装各种类型对象的泛型类.因为我使用泛型,所以我不能使用@delegate注释(因为它不适用于泛型,def或Object类型).相反,我利用methodMissing和propertyMissing方法传递方法调用和对封装对象的属性访问.我遇到的问题是如何委托调用DefaultGroovyMethods添加的方法(每个,收集,唯一等).我试过做以下事情:
protected void setObject(T object)
{
// Save the object
this.object = object
// Delegate all the default Groovy methods to the object
DefaultGroovyMethods.class.methods*.name.unique().each({ name ->
this.metaClass.'static'."${name}" = this.object.&"${name}"
})
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,这根本不起作用.甚至可以通过元类覆盖默认的Groovy方法吗?如果是,那么需要改变哪些才能使其工作?
不确定这是不是你想要的,但你的意思是这样的?
@groovy.transform.TupleConstructor
class Wrapper<T> {
T wrapped
def methodMissing(String name, args) {
if(wrapped.respondsTo(name)) {
wrapped."$name"(*args)
}
else {
throw new MissingMethodException(name, Wrapper, args)
}
}
def propertyMissing(String name) {
if(wrapped.hasProperty(name)) {
wrapped."$name"
}
else {
throw new MissingPropertyException(name, Wrapper)
}
}
String toString() {
"Wrapper(${wrapped.toString()})"
}
}
Wrapper<String> str = new Wrapper('tim')
assert str.length() == 3
assert str.bytes == [116, 105, 109]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
593 次 |
| 最近记录: |