The type erasure page says that
Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded. The produced bytecode, therefore, contains only ordinary classes, interfaces, and methods.
However, for the following class:
public class Foo<E extends CharSequence> {
public E something;
}
javap -c Foo
prints:
public class Foo<E extends java.lang.CharSequence> {
public E something;
}
Why is the type parameter not replaced with the bound (CharSequence), but is preserved as E?
It acts similar to an assembler which is an alias representation of a C++ code. As soon as a java program is compiled, java bytecode is generated. In more apt terms, java bytecode is the machine code in the form of a .class file. With the help of java bytecode we achieve platform independence in java. How does it works?
After the first compilation, the bytecode generated is now run by the Java Virtual Machine and not the processor in consideration. This essentially means that we only need to have basic java installation on any platforms that we want to run our code on.
A significant portion of the Java data structures use type parameters, which enables them to handle different types of variables. ArrayList, for instance, receives a single type parameter, while HashMap receives two. From here on out when you see the type ArrayList<String>, you know that its internal implementation uses a generic type parameter.
With the help of java bytecode we achieve platform independence in java. How does it works? When we write a program in Java, firstly, the compiler compiles that program and a bytecode is generated for that piece of code. When we wish to run this .class file on any other platform, we can do so.
What you printed isn't bytecode. It is the method signature. It's put there so the compiler can enforce typesafety when compiling other classes that call it.
Type information is preserved on classes and methods, but not on actual variables. If you wrote
class Foo extends Bar<String> {
}
...you could extract Bar<String>
at runtime, but if you had
new Bar<String>();
...you could not extract Bar<String>
there.
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