首页 文章

Groovy - 将DefaultGroovyMethods方法委托给通用对象

提问于
浏览
1

我有一个封装各种类型对象的泛型类 . 因为我使用泛型,所以我不能使用@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}"
  })
}

不幸的是,这根本不起作用 . 甚至可以通过元类覆盖默认的Groovy方法吗?如果是,那么需要改变哪些才能使其工作?

1 回答

  • 5

    不确定这是不是你想要的,但你的意思是这样的?

    @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]
    

相关问题