【问题标题】:Grails: ExpandoMetaClass for a methodGrails:方法的 ExpandoMetaClass
【发布时间】:2023-04-04 06:23:01
【问题描述】:

考虑一个方法

 def public Set<AgeRange> getAgeRanges(boolean excludeSenior) {
           -- something ---
     }

如何为此编写 ExpandoMetaClass

    ClassName.metaClass.methodName << { boolean excludeSenior->
           -- something ---
       }

【问题讨论】:

    标签: grails groovy expandometaclass


    【解决方案1】:

    我在 Groovy 控制台中尝试了这个,它成功了:

    class Something {
    
        Set getAgeRanges(boolean excludeSenior) {
            [1, 2, 3] as Set
        }
    }
    
    // test the original method
    def s = new Something()
    assert s.getAgeRanges(true) == [1, 2, 3] as Set
    
    // replace the method
    Something.metaClass.getAgeRanges = { boolean excludeSenior ->
        [4, 5, 6] as Set
    }
    
    // test the replacement method
    s = new Something()
    assert s.getAgeRanges(true) == [4, 5, 6] as Set
    

    【讨论】:

      【解决方案2】:

      我不太确定你在问什么,但这可能表明你在寻找什么:

      某类:

      class SomeClass {
          List<Integer> ages
      }
      

      为类添加方法的一些元编程:

      SomeClass.metaClass.agesOlderThan { int minimumAge ->
          // note that "delegate" here will be the instance
          // of SomeClass which the agesOlderThan method
          // was invoked on...
          delegate.ages?.findAll { it > minimumAge }
      }
      

      创建 SomeClass 的实例并调用新方法...

      def sc = new SomeClass(ages: [2, 12, 22, 32])
      
      assert sc.agesOlderThan(20) == [22, 32]
      

      这有帮助吗?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-11-18
        • 2011-08-08
        • 1970-01-01
        • 1970-01-01
        • 2014-10-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多