1

我有一个模糊的回忆,读到 groovy 存在一个 '??' 可用于使方法名称动态化的糖。我曾认为这就是如何在 grails 中实现动态查找器的,但现在我怀疑它是否甚至是我回忆的 groovy。举个例子:我用一些方法创建了一个类

class GroovyExample {

  public def getThingOne(){return '1'}

  public def getThingTwo(){return '2'}

  public def getModifiedThingOne(){
    return this.modify(this.thingOne)
  }

  //  *!!!*  I want to get rid of this second modifying method    *!!!*
  public def getModifiedThingTwo(){
    return this.modify(this.thingTwo)
  }

  private def modify(def thing){
    //...
    return modifiedThing
  }

}

方法名称是否有??糖,我可以用它来干燥它,如下所示:

class GroovyExample {

  public def getThingOne(){return '1'}

  public def getThingTwo(){return '2'}

  //  Replaced the two getModifiedXX methods with a getModified?? method I think I can do....
  public def getModified??(){
    return this.modify(this."${howeverYouReferenceTheQuestionMarks}")
  }

  private def modify(def thing){
    //...
    return modifiedThing
  }

}

这个想法是我可以new GroovyExample().modifiedThingTwo通过一种“修改辅助方法”来调用并获得相同的答案。这可能吗?叫什么???(我一辈子都不能用谷歌搜索它。)而且,我如何引用String“in” ??

4

1 回答 1

2

我不知道该语法,但您可以通过实现methodMissing()per here来实现该功能。根据该链接,这是您提到的动态查找器的初始作用机制(尽管我相信在第一次命中方法后会有一些缓存) - 请注意顶部的警告。

像这样的快速测试可能适合您:

   def methodMissing(String name, args) {
       switch (name) {
           case "getModifiedThingOne":
               return this.modify(this.thingOne)
           case "getModifiedThingTwo":
               return this.modify(this.thingTwo)              
       }
   }
于 2012-12-06T00:51:22.817 回答