When a generic type is instantiated, the compiler translates those types by a technique called type erasure — a process where the compiler removes all information related to type parameters and type arguments within a class or method. Type erasure enables Java applications that use generics to maintain binary compatibility with Java libraries and applications that were created before generics.
For instance, Box<String> is translated to type Box, which is called the raw type — a raw type is a generic class or interface name without any type arguments. This means that you can't find out what type of Object a generic class is using at runtime. The following operations are not possible:
public class MyClass<E> {
public static void myMethod(Object item) {
// Compiler error
if (item instanceof E) {
...
}
// Compiler error
E item2 = new E();
// Compiler error
E[] iArray = new E[10];
// Unchecked cast warning
E obj = (E)new Object();
}
}
The operations shown in bold are meaningless at runtime because the compiler removes all information about the actual type argument (represented by the type parameter E) at compile time.
For instance, Box<String> is translated to type Box, which is called the raw type — a raw type is a generic class or interface name without any type arguments. This means that you can't find out what type of Object a generic class is using at runtime. The following operations are not possible:
public class MyClass<E> {
public static void myMethod(Object item) {
// Compiler error
if (item instanceof E) {
...
}
// Compiler error
E item2 = new E();
// Compiler error
E[] iArray = new E[10];
// Unchecked cast warning
E obj = (E)new Object();
}
}
The operations shown in bold are meaningless at runtime because the compiler removes all information about the actual type argument (represented by the type parameter E) at compile time.
0 comments:
Post a Comment