加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Generics上的Groovy地图和Java地图

发布时间:2020-12-14 16:33:17 所属栏目:大数据 来源:网络整理
导读:我是Groovy的新手,我对使用map有疑问: 我知道我能做到: def map = [key:“value”] 但是如果我这样做意味着什么: Map String,String map = [“1”:1,“2”:“2”] 此代码编译,但地图实际上不是String- String映射: map.each({println it.key“:”it.
我是Groovy的新手,我对使用map有疑问:

我知道我能做到:

def map = [key:“value”]

但是如果我这样做意味着什么:

Map< String,String> map = [“1”:1,“2”:“2”]

此代码编译,但地图实际上不是String-> String映射:

map.each({println it.key“:”it.value“[”it.value.class“]”})

它打印:

1:1[class java.lang.Integer]

2:2[class java.lang.String]

任何人都可以帮助我理解如何使用String->明确键入地图?可以将字符串分配给包含String-> Integer的地图对象?谢谢!

===更新===

感谢@GrailsGuy提供的链接,如果我使用@TypeChecked包含在方法中的上述代码,它将抛出一个错误:

[静态类型检查] – 不兼容的通用参数类型.无法分配java.util.Map< java.lang.String,java.io.Serializable> to:java.util.Map< String,String>

这个解释现在很有意义.

解决方法

这篇 forum post讨论了Groovy无视泛型,特别是:

Groovy is a dynamically typed
language,but you can statically declare the types of variables.
Generics on the JVM are erased at compile time and only the raw type
is available to the VM (this is true both for groovy and Java). In
Java,there is compile time checking to ensure that you don’t stuff an
int into a list of strings. But,Groovy does not check types at
compile time.

So,this means that the type parameter is not checked at compile time and not available at runtime.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读