【问题标题】:Is it possible to add a methodMissing hook via a category in Groovy?是否可以通过 Groovy 中的类别添加 methodMissing 挂钩?
【发布时间】:2017-12-06 18:13:30
【问题描述】:

我想将methodMissing() 添加到我没有源代码控制权的类中。我试过了:

class MyClass {} // class I'm not allowed to edit

class MyCategory {

  static def methodMissing(MyClass self, String name, Object args) {
      "I was hoping this was called on a.nonexisting()"
  }

  static def test(MyClass self) {
      "test works"
  }
}

def a = new MyClass()

use(MyCategory) {
    println a.test()
    println a.nonexisting()    
}

但我仍然收到groovy.lang.MissingMethodException: No signature of method: MyClass.nonexisting() is applicable for argument types: () values: []

是否可以在课程中添加临时 methodMissing

我试图避免与元类混淆,因为该更改将是全局且不可逆的。

【问题讨论】:

    标签: java groovy


    【解决方案1】:

    根据 Groovy in Action,2015 年发布的第 2 版:

    类别方法名称可以很好地采用属性访问器的形式 (假装属性访问)、操作符方法和 GroovyObject 方法。 MOP 钩子方法(propertyMissing、methodMissing)不能通过类别添加 类。这是 Groovy 2.4 的限制。该功能可能会在以后的版本中提供。

    所以在 2.4.12 中是不可能做到的,

    release notes for Groovy 2.5(2017-11 仍在开发中)没有提到任何关于此的更改。

    release notes for Groovy 2.6 也别提了。

    最后不幸的是,release notes for Groovy 3.0methodMissing 只字不提

    【讨论】:

      猜你喜欢
      • 2018-05-21
      • 2015-04-20
      • 2013-10-05
      • 1970-01-01
      • 2016-08-02
      • 1970-01-01
      • 2015-09-01
      • 1970-01-01
      • 2023-03-04
      相关资源
      最近更新 更多