在使用闭包映射来实现Groovy中的接口时(如http://groovy.codehaus.org/Groovy+way+to+implement+interfaces ),有什么方法可以在使用后将对象转换回地图as关键字或asType方法来实现接口?
When using a map of closures to implement an interface in Groovy (as in http://groovy.codehaus.org/Groovy+way+to+implement+interfaces) is there any way to convert the object back to a map after using the as keyword or the asType method to implement the interface?
最满意答案
根据您的使用情况,似乎您可以在将其转换为所需的界面之前保留对原始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代码的内部结构,所以请自担风险:
Based on your use case it would seem that you could just keep a reference to the original Map before converting it into the needed interface.
However, looking at the source code that converts the Map object into the interface (using a Proxy), it looks like you can just re-retrieve the original map by getting the InvocationHandler's delegate.
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)Note: This depends on the internals of the Groovy code so use at your own risk:
更多推荐
发布评论