Java: getClass() of bounded type

前端 未结 5 1318
旧时难觅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条回答
  •  -上瘾入骨i
    2020-11-30 13:04

    You cannot be sure that value is actually a T, it could also be a subclass of T. getClass() does return the "real" class of value, but you can't be sure that's T, therfore it has to read Class! This has nothing to do with the fact that T is a type parameter.

    [Edit] Ok not quite, i didn't realize method2 doesn't compile. I think this is a compiler issue. I get

    Type mismatch: cannot convert from Class to Class
    

    I think the compiler only realizes that the T object is a Foo. The compiler should know getClass() returns some Class but only seems to know that it returns some Class. Does that mean Foo is the erasure of the static type of T?

提交回复
热议问题