Category: 06. Java Generics
-
No Overload
A class is not allowed to have two overloaded methods that can have the same signature after type erasure.
-
No Exception
A generic class is not allowed to extend the Throwable class directly or indirectly. A method is not allowed to catch an instance of a type parameter. Type parameters are allowed in a throws clause.
-
No Array
Arrays of parameterized types are not allowed. Because compiler uses type erasure, the type parameter is replaced with Object and user can add any type of object to the array. And at runtime, code will not able to throw ArrayStoreException.
-
No instanceOf
Because compiler uses type erasure, the runtime does not keep track of type parameters, so at runtime difference between Box<Integer> and Box<String> cannot be verified using instanceOf operator.
-
No Cast
Casting to a parameterized type is not allowed unless it is parameterized by unbounded wildcards. To achive the same, unbounded wildcards can be used.
-
No Static field
Using generics, type parameters are not allowed to be static. As static variable is shared among object so compiler can not determine which type to used. Consider the following example if static type parameters were allowed. Example As stringBox and integerBox both have a stared static type variable, its type can not be determined. Hence…
-
No Instance
A type parameter cannot be used to instantiate its object inside a method. To achieve such functionality, use reflection. Example This will produce the following result −
-
No Primitive Types
Using generics, primitive types can not be passed as type parameters. In the example given below, if we pass int primitive type to box class, then compiler will complain. To mitigate the same, we need to pass the Integer object instead of int primitive type. Example This will produce the following result − Output
-
Generic Methods Erasure
Java Compiler replaces type parameters in generic type with Object if unbounded type parameters are used, and with type if bound parameters are used as method parameters. Example In this case, java compiler will replace T with Object class and after type erasure,compiler will generate bytecode for the following code. In both case, result is…
-
Unbounded Types Erasure
Java Compiler replaces type parameters in generic type with Object if unbounded type parameters are used. Example In this case, java compiler will replace T with Object class and after type erasure,compiler will generate bytecode for the following code. In both case, result is same − Output