groovy使用范型的坑

java的范型

Map<String, Integer> map = new HashMap<>();
map.put("a", 100);
map.put(1, 200); // 在编译期就会报错

上面的代码在运行时,尽管有类型擦除,但是由于编译期有类型检查,map中的<key, value>的类型始终为<String, Integer>,可放心使用。

groovy的范型

public Map<String, Integer> func() {
    def map = new HashMap<>()
    map.put('a', 100)
    map.put(1, 200) // 在编译期不会报错
    map
}

上面的代码即使使用了@CompileStatic静态编译注解在编译期也不会报错。由于在运行时有类型擦除,所以func返回的Map的<key, value>的数据类型是不确定的,key的类型并不一定为String,比如使用map.get('1')来查询时是获取不到键值对的,这是一个坑点!!!

为了程序的严谨,个人建议使用java的强制类型编码风格,且使用@CompileStatic静态编译注解,改写后的代码如下。

public Map<String, Integer> func() {
    Map<String, Integer> map = new HashMap<>()
    map.put('a', 100)
    map.put(1, 200) // 在编译期就会报错
    map
}

猜你喜欢

转载自www.cnblogs.com/bluesky8640/p/10090257.html