V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
amiwrong123
V2EX  ›  Java

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

  •  
  •   amiwrong123 · Oct 10, 2019 · 2829 views
    This topic created in 2391 days ago, the information mentioned may be changed or developed.
    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  
       Oct 10, 2019
    因为只有 List.class 没有 List<Integer>.class
    Raymon111111
        2
    Raymon111111  
       Oct 10, 2019
    换个理解的方式

    List<Integer> 这么写只是为了编译检查用的, 所以不存在对应的 class
    amiwrong123
        3
    amiwrong123  
    OP
       Oct 10, 2019
    @chendy
    @Raymon111111
    对哈,从这个角度就好理解多了。不管是 List<Integer>,还是 List<String>,实际上编译生成的 Class 文件,永远只有一份。
    ZredoC
        4
    ZredoC  
       Oct 13, 2019
    泛型只是编译阶段为了防止输入错误类型而存在的,可以通过反射的 invoke 操作绕过编译,
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   4712 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 00:13 · PVG 08:13 · LAX 17:13 · JFK 20:13
    ♥ Do have faith in what you're doing.