Why should I care that Java doesn't have reified generics?

后端 未结 13 833
予麋鹿
予麋鹿 2020-11-28 02:59

This came up as a question I asked in an interview recently as something the candidate wished to see added to the Java language. It\'s commonly-identified as a pain that Jav

13条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-28 03:10

    Here's one that's caught me today: without reification, if you write a method that accepts a varargs list of generic items ... callers can THINK they're typesafe, but accidentally pass in any-old crud, and blow up your method.

    Seems unlikely that would happen? ... Sure, until ... you use Class as your datatype. At this point, your caller will happily send you lots of Class objects, but a simple typo will send you Class objects that don't adhere to T, and disaster strikes.

    (NB: I may have made a mistake here, but googling around "generics varargs", the above appears to be just what you'd expect. The thing that makes this a practical problem is the use of Class, I think - callers seem to be less careful :( )


    For instance, I'm using a paradigm that uses Class objects as a key in maps (it's more complex than a simple map - but conceptually that's what's going on).

    e.g. this works great in Java Generics (trivial example) :

    public  Set getEntitiesPossessingComponent( Class componentType)
        {
            // find the entities that are mapped (somehow) from that class. Very type-safe
        }
    

    e.g. without reification in Java Generics, this one accepts ANY "Class" object. And it's only a tiny extension of the previous code :

    public  Set getEntitiesPossessingComponents( Class... componentType )
        {
            // find the entities that are mapped (somehow) to ALL of those classes
        }
    

    The above methods have to be written out thousands of times in an individual project - so the possibility for human error becomes high. Debugging mistakes is proving "not fun". I'm currently trying to find an alternative, but don't hold much hope.

提交回复
热议问题