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 Java doesn't have reified generics but, when pushed, the candidate couldn't actually tell me the sort of things that he could have achieved were they there.
Obviously because raw types are allowable in Java (and unsafe checks), it is possible to subvert generics and end up with a List<Integer>
that (for example) actually contains String
s. This clearly could be rendered impossible were type information reified; but there must be more than this!
Could people post examples of things that they would really want to do, were reified generics available? I mean, obviously you could get the type of a List
at runtime - but what would you do with it?
public <T> void foo(List<T> l) { if (l.getGenericType() == Integer.class) { //yeah baby! err, what now?
EDIT: A quick update to this as the answers seem mainly to be concerned about the need to pass in a Class
as a parameter (for example EnumSet.noneOf(TimeUnit.class)
). I was looking more for something along the lines of where this just isn't possible. For example:
List<?> l1 = api.gimmeAList(); List<?> l2 = api.gimmeAnotherList(); if (l1.getGenericType().isAssignableFrom(l2.getGenericType())) { l1.addAll(l2); //why on earth would I be doing this anyway?
In Java, under the covers, they are the same thing - a List<Object> . This means that if you have one of each, you can't look at them at run time and see what they were declared as - only what they are now. The reified generics would change that, giving Java developers the same capabilities that exist now in .
Generics enable the use of stronger type-checking, the elimination of casts, and the ability to develop generic algorithms. Without generics, many of the features that we use in Java today would not be possible.
To overcome the above problems of collections(type-safety, type casting) generics introduced in java 1.5v . Main objectives of generics are: 1) To provide type safety to the collections. 2) To resolve type casting problems. To hold only string type of objects we can create a generic version of ArrayList as follows.
The thing that most commonly bites me is the inability to take advantage of multiple dispatch across multiple generic types. The following isn't possible and there are many cases where it would be the best solution:
public void my_method(List<String> input) { ... } public void my_method(List<Integer> input) { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With