Java Reference
In-Depth Information
The GenericArrayClass declares a type parameter T . In the constructor, it attempts to create an array of the
generic type. You cannot compile the above code. The compiler will complain about the following statement:
elements = new T[howMany]; // A compile-time error
Recall that all references to the generic type are erased from the code when a generic class or code using it
is compiled. An array needs to know its type when it is created, so that it can perform a check at runtime when
an element is stored in it to make sure that the element is assignment-compatible with its type. An array's type
information will not be available at runtime if you use a type parameter to create it. This is the reason that the above
statement is not allowed.
You cannot create an array of generic type because the compiler cannot ensure the type-safety of the assignment
to the array element. You cannot write the following code:
Wrapper<String>[] gsArray = null;
// Cannot create an array of generic type
gsArray = new Wrapper<String>[10]; // A compile-time error
It is allowed to create an array of unbounded wildcard generic types, as shown:
Wrapper<?>[] anotherArray = new Wrapper<?>[10]; // Ok
Suppose you want to use an array of a generic type. You can do so by using the newInstance() method of the
java.lang.reflect.Array class as follows. You will have to deal with the unchecked warnings at compile time
because of the cast used in the array creation statement. The following snippet of code shows that you can still bypass
the compile-time type-safety check when you try to sneak in an Object into an array of Wrapper<String> . However,
this is the consequence you have to live with when using generics, which does not carry its type information at
runtime. Java generics are as skin deep as you can imagine.
Wrapper<String>[] a = (Wrapper<String>[])Array.newInstance(Wrapper.class, 10);
Object[] objArray = (Object[])a;
objArray[0] = new Object(); // Will throw a java.lang.ArrayStoreExceptionxception
a[0] = new Wrapper<String>("Hello"); // OK. Checked by compiler
Runtime Class Type of Generic Objects
What is the class type of the object for a parameterized type? Consider the program in Listing 4-4.
Listing 4-4. All Objects of a Parameterized Type Share the Same Class at Runtime
// GenericsRuntimeClassTest.java
package com.jdojo.generics;
public class GenericsRuntimeClassTest {
public static void main(String[] args) {
Wrapper<String> a = new Wrapper<String>("Hello");
Wrapper<Integer> b = new Wrapper<Integer>(new Integer(123));
Class aClass = a.getClass();
Class bClass = b.getClass();
System.out.println("Class for a: " + aClass.getName());
 
Search WWH ::




Custom Search