Why do some claim that Java's implementation of generics is bad?

后端 未结 13 1824
挽巷
挽巷 2020-11-29 15:53

I\'ve occasionally heard that with generics, Java didn\'t get it right. (nearest reference, here)

Pardon my inexperience, but what would have made them better?

相关标签:
13条回答
  • 2020-11-29 16:51

    The main problem is that Java doesn't actually have generics at runtime. It's a compile time feature.

    When you create a generic class in Java they use a method called "Type Erasure" to actually remove all of the generic types from the class and essentially replace them with Object. The mile high version of generics is that the compiler simply inserts casts to the specified generic type whenever it appears in the method body.

    This has a lot of downsides. One of the biggest, IMHO, is that you can't use reflection to inspect a generic type. Types are not actually generic in the byte code and hence can't be inspected as generics.

    Great overview of the differences here: http://www.jprl.com/Blog/archive/development/2007/Aug-31.html

    0 讨论(0)
提交回复
热议问题