【问题标题】:What is the difference between invokeMethod and methodMissing?invokeMethod 和 methodMissing 有什么区别?
【发布时间】:2013-10-07 08:43:42
【问题描述】:

在 Groovy 中,invokeMethodmethodMissing 方法之间的主要区别是什么?是否有明确的指导方针何时应该使用其中一种方法?

【问题讨论】:

  • 前者用于拦截所有方法/属性访问,后者用于拦截失败方法/属性访问。详情here.

标签: groovy


【解决方案1】:

什么时候用什么: 始终使用 methodMissing。

@FooBarUser。感谢您将我指向包含错误文档的页面,该页面将很快更改。

invokeMethod 通常不会为每个方法调用调用,仅在某些情况下。这也是为什么要添加 methodMissing 的原因,目的是让方法具有明确的作用,不像有时回退,有时是前端方法 invokeMethod

【讨论】:

  • "invokeMethod 通常不会在每个方法调用中调用,仅在某些情况下" -- 哪些情况?据我了解,根据Groovy的拦截机制,就是方法缺失的时候和没有missingMethod()方法的时候。这基本上似乎与 missingMethod(); 相同。它只是发生在之后。
  • 我不是在谈论 missingMethod 案例,我的目标是 invokeMethod 有时是一个前端。这意味着,例如,如果您从 Java 调用 GroovyObject 上的方法,那么许多人使用 invokeMethod。这意味着它首先被调用——即使真正的方法存在。在 Groovy 中,如果您实现 GroovyInterceptable,您可以拥有相同的功能。这迫使首先从 Groovy 执行 invokeMethod ......在 Java 中,您仍然可以选择。而且因为 invokeMethod 是一个遗留问题,所以我总是告诉人们尽可能使用 methodMissing。
【解决方案2】:

有一个帖子here

在 Groovy 对未在类中定义的方法的调用抛出 MissingMethodException 之前,Groovy 首先通过对象的 methodMissing() 方法路由调用。这让程序员有机会拦截对这些不存在的方法的调用并为它们定义一个实现。

还有文档here

从 1.5 开始,Groovy 支持“methodMissing”的概念。这与 invokeMethod 的不同之处在于它仅在方法分派失败的情况下被调用。

1) 由于 method/propertyMissing 仅在调度失败的情况下发生, 它们的执行成本很高

2) 因为 method/propertyMissing 不会像拦截每个方法调用一样 invokeMethod 通过一些元编程技巧可以提高效率

【讨论】:

    【解决方案3】:
    在进行自定义委托时,

    invokeMethod() 似乎在decorator pattern Groovy doc 中使用了很多。例如:

    class TracingDecorator {
        private delegate
        TracingDecorator(delegate) {
            this.delegate = delegate
        }
        def invokeMethod(String name, args) {
            println "Calling $name$args"
            def before = System.currentTimeMillis()
            def result = delegate.invokeMethod(name, args)
            println "Got $result in ${System.currentTimeMillis()-before} ms"
            result
        }
    }
    

    话虽如此,def result = delegate.invokeMethod(name, args) 可以很容易地替换为更现代的 Groovy 成语 def result = delegate."$name"(*args)

    【讨论】:

      猜你喜欢
      • 2010-10-02
      • 2011-12-12
      • 2010-09-16
      • 2012-03-14
      • 2012-02-06
      • 2011-02-25
      • 2011-11-22
      • 2015-03-26
      • 2013-08-19
      相关资源
      最近更新 更多