Search⌘ K

Reification

Understand how reification affects generics in Java, especially the limitations and risks of casting generic types and creating arrays of generic elements. Learn why mixing generics with arrays can cause runtime exceptions and how to avoid these pitfalls in your code.

We'll cover the following...
1.

What is reification in Java?

Show Answer
Did you find this helpful?
Java
class Demonstration {
public static void main( String args[] ) {
Integer[] array = new Integer[10];
Number[] refToArray = array;
// Attempt to store a Double in an array of Integers
// throws ArrayStoreException
refToArray[0] = new Double(5);
}
}
1.

What is a reifiable type?

Show Answer
1 / 2
Java
import java.util.*;
class Demonstration<T> {
public static void main( String args[] ) {
Integer[] arr = new Integer[10];
System.out.println(arr instanceof Integer[]);
List<Integer> list = new ArrayList<>();
System.out.println(list instanceof List);
// list instanceof List<Integer> <--- compile time error
}
void testInstanceOf(Object o){
// instance of test with the generic type parameter
// System.out.println(o instanceof T); // <--- compile time error
}
}

Attempting to cast an object to a generic type e.g. T t = (T)someObj results in a compiler warning and there's a potential of getting a class cast exception at runtime. Similarly, we can cast a generic parameter to another type e.g. String someObj = (String)t without a compile time warning but a ...