Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why aren't Java generic type parameters reified at runtime?

Tags:

java

generics

My understanding is that C# and java differ with respect to generics in some ways, one of which is that generic type parameters are available at runtime in C#/.NET but not in Java. Why did the Java language designers do it this way?

like image 480
user46775 Avatar asked Dec 17 '08 01:12

user46775


2 Answers

To allow binary compatibility with pre-generics bytecode, therefore allowing new code to interface with old code.

From the Type Erasure page of The Java Tutorials:

Type erasure enables Java applications that use generics to maintain binary compatibility with Java libraries and applications that were created before generics.

[...]

Type erasure exists so that new code may continue to interface with legacy code.

For a related question, take a look at C# vs Java generics.

like image 190
coobird Avatar answered Oct 13 '22 01:10

coobird


I remember reading something about this in the book Hardcore Java:

The problem with checking elements in a collection at runtime is that it is extremely expensive; the order of efficiency is only O(n). If you have only 10 addresses in your collection, checking elements is easy. However, if the collection contains 15,000 addresses, then you would incur a significant overhead whenever someone calls the setter.

On the other hand, if you can prevent users from placing anything other than an address in your collection at compile time, then you wouldn't have to check the types at runtime. If they try to give you something that isn't an address, then the compiler will reject the attempt. This is exactly what parameterized types do.

However, "why" questions can never really be satisfactorily answered because there are just too many variable involved with people, time, place and politics. I remember reading somewhere else that the decision had a lot to do with maintaining compatibility with the way things were already being done in the Java byte code. Here is another quote from the same book:

After the compiler has resolved the type safety introduced by generics, it erases the parameterization from the type. Therefore, the information is not available at runtime. The purpose of erasure, as stated by Sun, is to allow class libraries built with an older version of the JDK to be able to run on the JDK 1.5 virtual machine.

I'm curious, what are the advantages offered by runtime generics?

like image 20
Elijah Avatar answered Oct 13 '22 01:10

Elijah