Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this type parameter preserved in the bytecode?

Tags:

java

generics

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?

like image 782
Bozho Avatar asked Nov 05 '14 22:11

Bozho


People also ask

What is Java bytecode?

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?

What happens to the bytecode after the first compilation?

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.

What is a type parameter in Java?

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.

How to achieve platform independence with Java bytecode?

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.


2 Answers

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.

like image 91
user207421 Avatar answered Nov 15 '22 20:11

user207421


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.

like image 27
Louis Wasserman Avatar answered Nov 15 '22 19:11

Louis Wasserman