Generics Type Erasure, its Effects and Bridge Methods
Its a technique used by the java compiler to do the following:
1) To replace/translate all parameterized type/ Generic type in Java Generics to raw types in bytecode.
2) To preserve type safety by inserting type casts if necessary.
3) To preserve polymorphism in extended generic types by generating bridge methods.
1) To replace/translate all parameterized type/ Generic type in Java Generics to raw types in bytecode.
2) To preserve type safety by inserting type casts if necessary.
3) To preserve polymorphism in extended generic types by generating bridge methods.
Erasure of Generic Types:
Erasure of Generic types is done by java compiler while compiling the source code. The main reason why we are using generics is to allow the programmer to write generic code with type safety. So programmers are not forced to write generic code. But its good coding practice to follow while coding Java.
GenericTypeErasureTest.java:
In the abovecode we instantiate generic list using the parameterized type as String for generic type.
Let us compile the above java code and get a binary class file. Then decompile the same using any Java decompiler of your choice as shown in figure below and check what type erasure has done.
Erasure of Generic Methods:
Similarly the Java compiler also erases type parameters in generic method arguments. Inspect using java decompiler or javap tool to see what java compiler has done.
Refer Example: Erasure of type parameters in generic methods
Refer Example: Erasure of type parameters in generic methods
Effects of Type Erasure and Bridge Methods:
Sometimes type erasure results in a situation, the compiler may need to create a synthetic method called bridge method, as a part of type erasure process. And you dont have to worry about those bridge methods if you happen to see such methods in the stack trace. Let us consider the following example to understand the effects of type erasure and bridge methods.
GenericClazz.java:
ExtGenericClazz.java:
ExtGenericClazzTest.java:
Compile the above source code. Then inspect using java decompiler or you can also use javap tool to inspect what compiler has done as shown in figure below:
Why these bridge methods are generated by compiler?
After type erasure the method signatures in the ExtGenericClazz may not match in such scenarios. To solve this problem and preserve polymorphism (Class extending parameterized class) of generic types after type erasure, the java compiler generates bridge methods to ensure that subtyping when you extend class should work as expected.
0 comments:
Post a Comment