【问题标题】:How to change behaviour of the method in groovy using that method in metaclass如何在元类中使用该方法更改 groovy 中方法的行为
【发布时间】:2010-10-29 13:36:16
【问题描述】:

我想通过以下方式“破坏”Groovy 中的 plus 方法:

Integer.metaClass.plus {Integer n -> delegate + n + 1}
assert 2+2 == 5

我得到了 StackOverflowException(这并不奇怪)。

有没有办法在元类的闭包中使用“原始”加法?

【问题讨论】:

    标签: groovy metaprogramming


    【解决方案1】:

    常规的惯用方法是保存对旧方法的引用并在新方法中调用它。

    def oldPlus = Integer.metaClass.getMetaMethod("plus", [Integer] as Class[])
    
    Integer.metaClass.plus = { Integer n ->
        return oldPlus.invoke(oldPlus.invoke(delegate, n), 1)        
    }
    
    assert 5 == 2 + 2
    

    这实际上并没有那么好记录,我打算在今晚或明天发表一篇关于这个确切主题的博客文章:)。

    【讨论】:

      【解决方案2】:

      用这个“宠”加法:

      Integer.metaClass.plus {Integer n -> delegate - (-n) - (-1)}
      assert 2+2 == 5
      

      毫不奇怪,在重载plus方法中使用'+'操作符会导致StackOverflow,需要使用'+'操作符以外的东西。

      其他机制:使用 XOR 或一些位运算符魔法。

      问候, 和平之火

      【讨论】:

      • 看来Groovy 1.6 很聪明,可以将调用委托- (-n) 改为delegate + n 并且仍然抛出StackOverflowException
      • hmm.. 我的版本是 Groovy 1.6 和 Java 1.5.0_15 我在 groovy 控制台中运行它,它运行良好而没有抛出任何 StackOverflowException 我在 groovyshell 中运行它运行良好。你是如何尝试运行上面的脚本的?
      • 刚刚看到 Ted 上面发布的答案。我认为这是更好的通用解决方案。 +1 给泰德。
      猜你喜欢
      • 1970-01-01
      • 2020-08-05
      • 2023-01-04
      • 1970-01-01
      • 1970-01-01
      • 2016-04-21
      • 2019-06-21
      • 2012-09-22
      • 1970-01-01
      相关资源
      最近更新 更多