I'm a first time poster, so big hello to you all!
I'm currently reading Java Generics (O'Reilly) and I've been trying to figure out exactly what is meant by 'The principle of truth in advertising'.
The definition given is: " The reified type of an array must be a subtype of the erasure of its static type." (page 86)
I feel that book could be a little clearer in its explanation, but I believe that I have worked out what this means.
Essentially, all I am asking folks is whether I have understood this principle correctly, so here's what I think:
The reified type of an array can be found by calling getClass().getComponentType() on it. In the following code, the component type of objArr1 is String, thus the reified type is String[]
String[] strArr1 = {"hello", "world"}; Object[] objArr1 = strArr1; System.out.println("objArr1: reified type is: " + objArr1.getClass().getComponentType());
The static type of objArr1 is Object[], and after erasure, it is still Object[].
Thus objArr1 has a static type after erasure of Object[] and a reified type of String[]
String[] is a subtype of Object[], so all is well and the above code runs without any problems.
The following code produces a ClassCastException at runtime, however. This is because the reifiable type of objArr2 is Object[], which is not a subtype of the erasure of the static type of strArr2, which is String[]
Object[] objArr2 = {"hello", "world"}; String[] strArr2 = (String[]) objArr2;
But the following code does work, perhaps surprisingly. Calling getClass().getComponentType on objArr3 reveals it's reifiable type to be String[] rather than Object[]. i.e. The reified type of objArr3 is String[] which is a subtype of the erasure of strArr4's static type, which is also String[]
String[] strArr3 = {"hello", "world"}; Object[] objArr3 = strArr3; String[] strArr4 = (String[]) objArr3;
That's it! Thanks in advance for any feedback.