Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 Strings. 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? 
like image 562
oxbow_lakes Avatar asked Dec 18 '09 11:12

oxbow_lakes


People also ask

What is meant by reified generics in Java?

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 .

Why are generics in Java important?

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.

Why generics are introduced in Java What problems do they overcome?

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.


1 Answers

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) { ... } 
like image 176
RHSeeger Avatar answered Oct 19 '22 22:10

RHSeeger