Java’s generics would erase the type information after the source code was compiled. And i guess the “erase” is necessary because java only keep one copy of class no matter what the generic type is. So List<String> or List<Number> are simply just one List. Then I wonder if it possible that at the premise of keeping only one copy of certain class, the instance of the class stores the generic type information at the time it is created.
For instance:
when we write:
List<String> list = new List<String>.
the compiler create an object of List along with a String’s Class Object(meaning the Object String.class) accociated with the List, so that the generic object list can check the type information at runtime using the Class Object. Is it posssible or practicable?
I’m not entirely sure what you’re asking specifically, but the big reason Java has to use erasure for generics is backwards compatibility. If the behaviour of
…was altered between versions, when you upgraded from say Java 1.4 to Java 5, you’d have all sorts of weird things going on potentially causing bugs where the code didn’t behave in the same way as previously. That’s definitely a bad thing if that happens!
If they didn’t have to preserve backwards compatibility then yes, they could’ve done what they liked – we could’ve had nice reified generics and done a whole bunch of other stuff we couldn’t do now. There was a proposal (by Gafter I think) that would’ve allowed reified generics in Java in a backwards compatible way, but it would’ve involved creating new versions of all the classes that should have been generic. That would’ve caused a load of mess with the API, so (for better or worse) they chose not to go down that route.