将实现一个接口的Groovy地图转换回地图(Convert Groovy map implementing an interface back to a map)

编程入门 行业动态 更新时间:2024-10-07 13:17:06
将实现一个接口的Groovy地图转换回地图(Convert Groovy map implementing an interface back to a map)

在使用闭包映射来实现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:

更多推荐

本文发布于:2023-08-04 02:45:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1408576.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:地图   接口   Groovy   Convert   implementing

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!