Principle of Truth in Advertising
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[]
Code :
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[]
Code :
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[]
Code :
String[] strArr3 = {"hello", "world"};
Object[] objArr3 = strArr3;
String[] strArr4 = (String[]) objArr3;
That's it! Thanks in advance for any feedback.
Re: Principle of Truth in Advertising
This is a guess :p.
When you do something like this:
Code java:
Object[] objArr = {"a", "b", "c"};
You are not creating an array of strings. You are creating an array of objects. Or rather, it is an array of references to objects. These object will be strings in this case, but they could just as well be something else. For example, you can do this to illustrate what I mean:
Code java:
Object[] objArr = {"a", "b", 'c', 1};
For the same reason you cannot cast that to a String[] you cannot cast the first one. However, the first one may be more confusing to understand.
There is a way around this. You can do like this instead: