泛型的Groovy映射和Java映射 [英] Groovy map and Java map on Generics

查看:94
本文介绍了泛型的Groovy映射和Java映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Groovy的新手,我有一个关于使用map的问题:

我知道我可以这样做:



def map = [key:value]

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



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



这段代码编译完成,但是map并不是真的字符串 - >字符串映射:



map.each({println it.key +:+ it.value +[+ it它打印:


1:1 [class java.lang.Integer]



2:2 [class java.lang.String]


任何人都可以帮助我理解如何将一个使用String-> String显式类型的地图分配给包含String-> Integer的地图对象?谢谢!



===更新===

感谢@GrailsGuy提供的链接,if我正在使用 @TypeChecked 获取包装在方法中的上述代码,它会抛出一个错误:
$ b $ [静态类型检查] - 不兼容的泛型参数类型。无法指定java.util.Map< java.lang.String,java.io.Serializable> to:java.util.Map< String,String>



现在的解释非常有意义。


Groovy是一个动态类型化的
语言,但您可以静态声明变量的类型。
JVM上的泛型在编译时被擦除,只有原始类型
可用于VM(groovy和Java都适用)。在
Java中,有编译时检查,以确保不会将
int填充到字符串列表中。但是,Groovy并没有在
编译时检查类型。



所以,这意味着类型参数在编译时
时不被检查,在运行时可用。



I am new to Groovy, and I have a question regarding to the use of map:

I know I can do:

def map = [key:"value"]

But what does it mean if I do this:

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

This code compiles, but the map is not really a String->String map:

map.each({println it.key + ":" + it.value + "[" + it.value.class + "]"})

It prints:

1:1[class java.lang.Integer]

2:2[class java.lang.String]

Can anyone helps me to understand how come a map explicitly typed with String->String can be assigned to a map object that contains String->Integer? Thank you!

=== Update ===

Thanks for the link provided by @GrailsGuy, if I am using @TypeChecked for the above code wrapped in a method, it will throw an error:

[Static type checking] - Incompatible generic argument types. Cannot assign java.util.Map <java.lang.String, java.io.Serializable> to: java.util.Map <String, String>

The explanation makes perfect sense now.

解决方案

This forum post talks about Groovy ignoring generics, specifically:

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.

这篇关于泛型的Groovy映射和Java映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆