V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
amiwrong123
V2EX  ›  Java

List<Integer>.class 编译通不过,如何解释

  •  
  •   amiwrong123 · 2019-10-10 22:44:00 +08:00 · 2399 次点击
    这是一个创建于 1658 天前的主题,其中的信息可能已经有所发展或是发生改变。
    import java.io.*;
    import java.util.*;
    
    public class ClassCasting {
        //@SuppressWarnings("unchecked")
        public void f(String[] args) throws Exception {
            ObjectInputStream in = new ObjectInputStream(
                    new FileInputStream(args[0]));
        List<Integer> shapes = (List<Integer>)in.readObject();
    
            // Won't Compile:
        //List<Integer> lw1 = List<Integer>.class.cast(in.readObject());
            List lw2 = List.class.cast(in.readObject());
            List<Integer> lw3 = List.class.cast(in.readObject());
        }
        public static void main(String[] args) { }
    } ///:~
    

    这是 java 编程思想里面的一个小例子,里面有个小知识点。就是 List<Integer>.class 这样用不可以,但 List.class 这样用是可以的。

    这里我用自己的话解释一波:因为泛型是假泛型,所以 Class 对象(public final class Class<T>)只能记住泛型类的原生类型 raw type。这么解释对吗?

    chendy
        1
    chendy  
       2019-10-10 23:21:40 +08:00
    因为只有 List.class 没有 List<Integer>.class
    Raymon111111
        2
    Raymon111111  
       2019-10-10 23:39:29 +08:00
    换个理解的方式

    List<Integer> 这么写只是为了编译检查用的, 所以不存在对应的 class
    amiwrong123
        3
    amiwrong123  
    OP
       2019-10-10 23:42:02 +08:00
    @chendy
    @Raymon111111
    对哈,从这个角度就好理解多了。不管是 List<Integer>,还是 List<String>,实际上编译生成的 Class 文件,永远只有一份。
    ZredoC
        4
    ZredoC  
       2019-10-13 16:08:16 +08:00
    泛型只是编译阶段为了防止输入错误类型而存在的,可以通过反射的 invoke 操作绕过编译,
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5301 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 08:00 · PVG 16:00 · LAX 01:00 · JFK 04:00
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.