Java: getClass() of bounded type

前端 未结 5 1348
旧时难觅i
旧时难觅i 2020-11-30 12:35

I noticed something while I was derping around with generics. In the example below, doStuff1 compiles but doStuff2 doesn\'t:

public         


        
5条回答
  •  甜味超标
    2020-11-30 12:57

    Very good question.

    The whole problem with java generics is that they didn't exist in old virtual machines. Sun decided to add generic support while existing virtual machine did not support them.

    This could be a big problem, because when they release the new Java, old virtual machines would NOT be able to run any code written for the newest version of Java, and they would not have been able to legacy-support old virtual machines.

    So, they decided to implement generics in a way that they could also be run in old virtual machines. They decided to ERASE THEM FROM BYTECODE.

    So the whole story is about back-support of jvms.

    EDIT: But this had maybe nothing to do with the question. See kutschkem's answer!

    Also, my guess is that in the second case, the cast is Class to Class. This cast is only possible if List directly extends T (since it is an implicit cast). But its the other way around, T extends List.

    I think its the same thing as saying:

    String s = "s";
    Object o = s;
    

    In the above case, the cast is possible because String extends Object. For the inverse, you would need an explicit cast.

    If you add an explicit cast to your program, it compiles:

    public  void doStuff2(T value) {
       Class theClass = (Class) value.getClass();
    }
    

提交回复
热议问题