Java: getClass() of bounded type

前端 未结 5 1345
旧时难觅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 13:14

    If getClass() returns Class, nothing really bad can happen; actually it'll help a lot of use cases.

    The only problem is, it is not theoretically correct. if an object is an ArrayList, its class cannot be Class> - there is no such class, there is only a Class.

    This is actually not related to erasure. If one day Java gets full reified types, getClass() should still return Class; however there should be a new method, like getType() which can return a more detailed Type. (though, getType may conflict with a lot of existing classes with their own getType methods)

    For the timing being, since Class might be useful in a lot of cases, we can design our own method that does that

    static  Class myGetClass(X x){ ... }
    

    but it's understandable they wouldn't put this kind of hack in standard lib.

提交回复
热议问题