【问题标题】:can not override invokeMethod inherited from GroovyObject不能覆盖从 GroovyObject 继承的 invokeMethod
【发布时间】:2013-06-30 21:44:56
【问题描述】:

由于每个 Groovy 对象都实现了 GroovyObject 接口,我会尝试重写 invokeMethod(),这是我的测试:

class MyGrrovyClass {

  static test(){
      println 'i am in test'
  }

  Object invokeMethod(String name, Object args){
    log.info('method intercepted')
    def metaClass = InvokerHelper.getMetaClass(this)
    def result = metaClass.invokeMethod(this, name, args)
    return result
  }

  public static void main(String[] args) {
    test()
  }
}

但它似乎不起作用,我从未在控制台中看到日志消息

我的第二个问题是:GroovyInterceptable 是 GroovyObject 的子接口,我直接覆盖 GroovyObject 的 invokeMethod 和我实现 GroovyInterceptable 接口的 invokeMethod 有什么区别?

谢谢

【问题讨论】:

    标签: groovy metaprogramming


    【解决方案1】:

    根据文档 (http://groovy.codehaus.org/Using+invokeMethod+and+getProperty),您必须实现 GroovyInterceptable 来拦截现有方法,我认为这回答了您的第一个和第二个问题!

    我做了一些细微的改变来让你的示例类工作,虽然很惊讶地看到我的 println 被拦截但不是 System.out.println - 这意味着我遇到了堆栈溢出,因为我最初有一个简单的 println 在invokeMethod 并且被递归调用。

    class MyGrrovyClass implements GroovyInterceptable {
    
    
        def test(){
            println 'i am in test'
        }
    
    
        def invokeMethod(String name, args){
    
            System.out.println('method intercepted: '+ name)
    
            def result= metaClass.getMetaMethod(name, args).invoke(this, args)
        }
    }
    
    def mgc= new MyGrrovyClass()
    mgc.test()
    

    【讨论】:

      猜你喜欢
      • 2015-02-14
      • 2019-06-29
      • 1970-01-01
      • 1970-01-01
      • 2013-12-10
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      相关资源
      最近更新 更多