Java generics uses Types. If you are not still using java generics, following example code explains you a simple generics usage:
package com.javapapers.sample;
import java.util.HashMap;
import java.util.Map;
public class TypeErasure {
public static void main(String args[]) {
Map<String, String> languageMap = new HashMap<String, String>();
languageMap.put("1954", "FORTRAN");
languageMap.put("1958", "LISP");
languageMap.put("1959", "COBOL");
String language = languageMap.get("1954");
System.out.println("Our favourite language is "+language);
}
}
In the above code, we instantiate a map saying that the key and values will be String. These are type parameters. It provides you type safety.
Type erasure is a process to remove the types and map it to byte code. Just trying to give a formal definition for type erasure ;-) Type erasure happens at compile time. Java compiler removes those generic type information from source and adds casts as needed and delivers the byte code. Therefore the generated byte code will not have any information about type parameters and arguments. It will look like a old java code without generics. You want to have a look at it?

New as Old!
Compile above given source and get a class file. Then de-compile that generate class file and you will know what is inside. You may use JAD to de-compile. Else you can avoid the round trip and use the JDK itself directly on java source and find out how the compiled source will look like. javac -XD-printflat -d .java
package com.javapapers.sample;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.Map;
public class TypeErasure
{
public TypeErasure()
{
}
public static void main(String args[])
{
Map languageMap = new HashMap();
languageMap.put("1954", "FORTRAN");
languageMap.put("1958", "LISP");
languageMap.put("1959", "COBOL");
String language = (String)languageMap.get("1954");
System.out.println((new StringBuilder("Our favourite language is ")).append(language).toString());
}
}
You should note two things in the above de-compiled code.
- First thing is, “<String, String>” is missing.
- Second thing is (String)languageMap.get(“1954″) a type cast is added.
This is done by the java compiler while compiling java source code to byte code. This process is called java type erasure.
Main reason behind having type erasure at compile time is to give compatibility with old versions of java code where you don’t have generics. If you look at the definition of Map intereface using source available in JDK (beyond 1.5 ), it will be like
public interface Map<K,V> {
So if you use the Map without generics that should work with latest code. Thats why the java type erasure is brought in. When you use generics compiler checks whether you use all you type properly or not. If something is wrong you get an error at compile time and you need not wait until run time and blow up your production.
Consequences of Type Erasures
A java class with parametrized type cannot be instantiated as it requires a call to constructor. At run-time the type is not available because of type erasure and the instantiation cannot be done.
T instantiateElementType(List<T> arg)
{
return new T(); //causes a compilation error
}
Because of type erasure, at run-time you will not be able to find out what was the predefined type. There are hacks available using Reflection, but it is not guaranteed that it will work in all cases. It is also not a formal way.
There is lots of discussions on whether you need type erasure or is it implemented in a good way is going around. Leave that aside. If you use java, its better to use generics as much as possible. Advantage you get in using generics is type safety and clarity in your code. Though type erasure is good or bad, better know about it. Because it is the one that translates your generic java code to byte code.
















Good analysis….
Muthukumar on August 2nd, 2010 6:04 amHi,
Interesting blog you got. This is like a haven for java devs! I blog about Java too but with all other technologies. Anyway, nice article about type erasures. I haven’t really heard of this yet and I need sometime to absorb all that I’ve read so far…
Pinoy Java Blog on August 7th, 2010 9:15 amtest
sdf on November 18th, 2010 5:18 pmgood catching………..
hoque on November 19th, 2010 6:21 amNice catch there , hence i can not see with someone bother use type erasure as a programming technique instead of generics , only use i know of type erasure is to maintain binary compatibility with Java libraries and applications that were created before generics.
Keep up the good work mate !
gchatzip on December 12th, 2010 9:48 pmThe problem with the article is that it’s wrong on the class file thing.
Type erasure doesn’t erase generic type information when compiling source to the .class file. The example with JAD only shows that JAD doesn’t interpret generics metadata in the class file.
The erasure takes place during runtime, when objects are instantiated.
Have a look: http://stackoverflow.com/questions/339699/java-generics-type-erasure-when-and-what-happens
Olo on January 12th, 2011 6:58 pmBTW, also see this article:
http://www.ibm.com/developerworks/java/library/j-cwt02076.html
“In this article, I’ll show how you can use ASM both to retrieve the raw generics information out of class files and to interpret the generics in a useful manner. Before digging into the ASM details, I’ll start off with a look at how generics information is actually encoded into the binary classes.”
Olo on January 12th, 2011 7:06 pmBTW2, you can very easily test this without resorting to JAD decompilation.
Just make a class with a method that accepts of returns a generic type. That might even be a private method:
import java.util.LinkedList;
import java.util.List;
public class GenericList {
public static void main(String[] args) {
List numberList = new LinkedList();
numberList.add(Integer.valueOf(3));
numberList.add(Long.valueOf(Long.MAX_VALUE));
printList(numberList);
}
private static void printList(List printedList) {
System.out.println(“List: ” + printedList);
}
}
Compile the class:
javac GenericList.java
Have a look at its contents:
$ hexdump -C GenericList.class | less -in
What you’ll see:
….
000000b0 73 74 01 00 13 28 4c 6a 61 76 61 2f 75 74 69 6c |st…(Ljava/util|
000000c0 2f 4c 69 73 74 3b 29 56 01 00 09 53 69 67 6e 61 |/List;)V…Signa|
000000d0 74 75 72 65 01 00 28 28 4c 6a 61 76 61 2f 75 74 |ture..((Ljava/ut|
000000e0 69 6c 2f 4c 69 73 74 3c 2b 4c 6a 61 76 61 2f 6c |il/List;)V.|
….
Where did that java/lang/Number come from?
If type erasure really did remove the generic information from compiled class file, there would be no mention of java.lang.Number as it exists only in generic declarations in the source! As you can see, the exact information about printList() method’s generic argument is placed in the “Signature” section of the class file.
See also the official specification of Java class file format, section 4.4.4:
http://java.sun.com/docs/books/vmspec/2nd-edition/ClassFileFormat-final-draft.pdf
“4.4.4 Signatures
Olo on January 12th, 2011 7:50 pmSignatures are used to encode Java programming language type information that is
not part of the Java virtual machine type system, such as generic type and method
declarations and parameterized types. See The Java Language Specification, Third
Edition, for details about such types.
This kind of type information is needed to support reflection and
debugging, and by the Java compiler.”
Heck, in my previous post the generics were cut out from Java source, probably because of HTML tag filtering :(
On the other hand, it seems that the blog engine does its own type erasure ;)
Trying again with HTML entities:
import java.util.LinkedList;
import java.util.List;
public class GenericList {
public static void main(String[] args) {
List<Number> numberList = new LinkedList<Number>();
numberList.add(Integer.valueOf(3));
numberList.add(Long.valueOf(Long.MAX_VALUE));
printList(numberList);
}
private static void printList(List<? extends Number> printedList) {
Olo on January 12th, 2011 7:53 pmSystem.out.println(“List: ” + printedList);
}
}
Cool Site :-)
j0hn on January 21st, 2011 6:37 amIt’s good to read in this site..
Panneer on January 22nd, 2011 9:31 amIm going to prefer this to my friends!!
nice explanation for type erasure, superb answer
sumanta on May 18th, 2011 7:36 amIt really helps me to understand about type erasure with the generics example.
Really nice job :)
Bhabani Padhy on May 25th, 2011 8:06 amCan you explain Java Generics more in Detail in your next post?
Anonymous on January 24th, 2012 3:54 amhi,
This is nice concept,At first time i heard in this . I like this subject very much .Thanks for guide.
sathiya on March 24th, 2012 10:21 pm