小编Ant*_*nas的帖子

如果嵌套方法参数不是类型安全的,Java泛型推断嵌套方法调用的对象而不是T

今天我遇到了javac关于泛型类型推理的奇怪行为.这是用于说明这种奇怪行为的示例类:

import java.util.Map;
import java.util.Collections;
import java.util.HashMap;
public class Test {

    protected <T> T strange(T t, Map<String, String> map) {
        return t;
    }

    protected void ok(Map<String, String> map) {}
    protected <T> T test(T t) {
        T res = strange(t , new HashMap<String, String>());
        //Doesn't work
        //res = strange(t, new <String, String>HashMap());
        ok(new <String, String>HashMap());
        res = strange(t, Collections.<String, String>emptyMap());
        //Doesn't work
        //res = strange(t, Collections.EMPTY_MAP);
        res = strange(t, (Map<String, String>) Collections.EMPTY_MAP);
        ok(Collections.EMPTY_MAP);
        return res;
    }
}
Run Code Online (Sandbox Code Playgroud)

注意//Doesn't …

java generics type-inference inferred-type

0
推荐指数
1
解决办法
621
查看次数

标签 统计

generics ×1

inferred-type ×1

java ×1

type-inference ×1