java.lang.ClassCastException: xxx cannot be cast to [C

kyaa111 4月前 ⋅ 139 阅读

上代码


public class Test {
    public static Map<String, Object> MAP = new HashMap<>(2);

    static {
        MAP.put("int", 1);
        MAP.put("string", "2");
    }

    public static void main(String[] args) {
        System.out.println(String.valueOf(get("int")));
        System.out.println(String.valueOf(get("string")));
    }

    public static <T> T get(String k) {
        Object o = MAP.get(k);
        return (T) o;
    }
}

这段代码会抛出如下异常

Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to [C
	at org.test.cast.Test.main(Test.java:22)

原因

将Test类反编译可以看到

System.out.println(String.valueOf((char[])get("int")));

编译器选择了重载方法String.valueOf(char[]), 实际类型是Integer, 转换自然报错了

重载算法

https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.12.2

如何解决

指定强转类型即可

System.out.println(String.valueOf((int)get("int")));

泛型与重载尽量不要放在一起使用