4 ms·
I keep seeing people bash Java's Generics because of type erasure - but what exactly is so awful about it? All the questions on stackoverflow where the answer i
by brazzy 17y ago
I keep seeing people bash Java's Generics because of type erasure - but what exactly is so awful about it? All the questions on stackoverflow where the answer is "impossible because of type erasure, or use this workaround" don't seem to be about terribly important or useful things.
- fauigerzigerk 17y agoThe most horrible thing about it is that all primitives have to be boxed using huge amounts of memory. And there are lots of other bad consequences like not being able to call a constructor for a type parameter. But Java's horrible generics implementation is only my second most pressing problem. The first being the lack of structured value types (i.e struct in C#). I am rewriting a C# app in Java right now and I'm being forced into extremely awful hacks to prevent memory consumption from exploding. To illustrate how bad the situation is let me tell you that I'm seriously thinking about rewriting everything in C++ :-)
- thejake 17y agoThe case that I've bumped up against several times is when trying to get the class of the generic object. Something like: T obj; obj = getObjFromSomewhere(); log(T.class); This type of operation is most useful if writing framework type of some sort. I've come across it when trying to write a generic JPA base DAO type of class.
- rit 17y agoScala has Manifests to emulate reified types for just this reason. http://www.scala-blogs.org/2008/10/manifests-reified-types.html http://www.scala-blogs.org/2008/10/manifests-reified-types.h... It's improved a bit in 2.8 - in porting some code I discovered a nice little hack that lets you declare your variance like this: [A <: SomeBaseClass <: Manifest] Which tells the compiler in an oh so gentle manner to reify for you.
- jared314 17y agoIt is useful for doing metaprogramming, while keeping it type safe and well specified.
- bad_user 17y agoJava's Generics are awful because they are useless, while being the most complex feature added to Java. Templates in C++ or the generic types from Haskel enable parametric polymorphism which is a lot more elegant for certain problems than subtype-polymorphism (i.e. OOP). Java's generics is only a hack to make it look as though some piece of code that's using subtype-polymorphism is parametric ... but it only saves you explicit type-casts, which are also useless. dotNet's generics are different ... while sharing the same limitations (i.e. no late binding and not implicit interfaces), because the types are available at runtime the runtime dispatches being made aren't just hacks and you can use the reflection mechanism to workaround many of the problems associated.