Why is this parameter stored in byte code?

A page like erasure says that

Replace all type parameters in generic types with their boundaries or object, if the type parameters are not limited. Thus, the obtained bytecode 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 by a border (CharSequence), but saved as E?

+6
source share
3 answers

What you printed is not a bytecode. This is the signature of the method. It is placed there, so the compiler can provide type safety when compiling other classes that call it.

+7
source

Type information is stored on classes and methods, but not on real variables. If you wrote

 class Foo extends Bar<String> { } 

... you can extract the Bar<String> at runtime, but if you have

 new Bar<String>(); 

... you could not extract the Bar<String> there.

+2
source

The type parameter is retained because it must be known for subclassification. Definitions

 public class Foo<E extends CharSequence> 

and

 public class Foo<CharSequence> 

NOT equal, since the latter did not allow the subclass to be declared, say:

 public class MyStringFoo extends Foo<String> { } 

whereas the previous one does.

0
source

Source: https://habr.com/ru/post/977791/


All Articles