【发布时间】:2012-02-28 19:20:27
【问题描述】:
在 Groovy 中使用闭包映射实现接口时(如http://groovy.codehaus.org/Groovy+way+to+implement+interfaces),在使用 as 关键字或 asType 方法实现接口后,有什么方法可以将对象转换回映射?
【问题讨论】:
标签: groovy
在 Groovy 中使用闭包映射实现接口时(如http://groovy.codehaus.org/Groovy+way+to+implement+interfaces),在使用 as 关键字或 asType 方法实现接口后,有什么方法可以将对象转换回映射?
【问题讨论】:
标签: groovy
根据您的用例,您似乎只需保留对原始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 代码的内部结构,因此使用风险自负:
【讨论】:
有趣的问题...简短的回答,不。长答案,也许......假设你有这样的事情:
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 ]
然而,由于这是一个映射,任何包含多个具有相同名称和不同参数的方法的类都会失败。我也不确定在第一种情况下这样做有多明智......
您感兴趣的用例是什么?
【讨论】: