【问题标题】:Convert Groovy map implementing an interface back to a map将实现接口的 Groovy 映射转换回映射
【发布时间】:2012-02-28 19:20:27
【问题描述】:

在 Groovy 中使用闭包映射实现接口时(如http://groovy.codehaus.org/Groovy+way+to+implement+interfaces),在使用 as 关键字或 asType 方法实现接口后,有什么方法可以将对象转换回映射?

【问题讨论】:

    标签: groovy


    【解决方案1】:

    根据您的用例,您似乎只需保留对原始Map 的引用,然后再将其转换为所需的接口。

    但是,查看将Map 对象转换为接口的源代码(使用Proxy),您似乎可以通过获取InvocationHandler 的委托重新检索原始地图。

    def i = 1
    def m = [ hasNext:{ true }, next:{ i++ } ]
    Iterator iter = m as Iterator
    
    def d = java.lang.reflect.Proxy.getInvocationHandler(iter).delegate
    assert d.is(m)
    

    注意:这取决于 Groovy 代码的内部结构,因此使用风险自负:

    【讨论】:

      【解决方案2】:

      有趣的问题...简短的回答,不。长答案,也许......假设你有这样的事情:

      def i = 1
      Iterator iter = [ hasNext:{ true }, next:{ i++ } ] as Iterator
      

      然后调用

      println iter.take( 3 ).collect()
      

      打印[1,2,3]

      现在,您可以声明一个方法来执行此操作:

      def mapFromInterface( Object o, Class... clz ) {
        // Get a Set of all methods across the array of classes clz
        Set methods = clz*.methods.flatten()
        // Then, for each of these
        methods.collectEntries {
          // create a map entry with the name of the method as the key
          // and a closure which invokes the method as a value
          [ (it.name): { Object... args ->
                         o.metaClass.pickMethod( it.name, it.parameterTypes ).invoke( o, args )
          } ]
        }
      }
      

      然后您可以这样做:

      def map = mapFromInterface( iter, Iterator )
      

      然后调用:

      println map.next()
      println map.next()
      

      将打印4,后跟5

      使用println map 打印地图给出:

      [ remove:ConsoleScript43$_mapFromInterface_closure3_closure4@57752bea,
        hasNext:ConsoleScript43$_mapFromInterface_closure3_closure4@4d963c81,
        next:ConsoleScript43$_mapFromInterface_closure3_closure4@425e60f2 ]
      

      然而,由于这是一个映射,任何包含多个具有相同名称和不同参数的方法的类都会失败。我也不确定在第一种情况下这样做有多明智......

      您感兴趣的用例是什么?

      【讨论】:

      • 我经常使用 Groovy 为 Java 代码编写单元测试,并且经常使用闭包映射作为快速而肮脏的方式来删除我的测试单元所依赖的接口(因为我发现它比大多数当我真的不关心验证交互时模拟库)。有时我想设置一个“原型”存根接口并针对不同的测试场景进行一些调整,但如果不能将其转换回地图,我就无法做到。
      • @WillGorman 对于您的用例,plecong's answer 可能比我的更好更干净 :-)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-30
      • 1970-01-01
      • 1970-01-01
      • 2014-03-10
      • 1970-01-01
      相关资源
      最近更新 更多