Consider the following example, ignoring the reason one would want to do this:
private static class Original {
public String getValue() {
return "Foo";
}
}
private static class Wrapper extends Original {
private Original orig;
public Wrapper(Original orig) {
this.orig = orig;
}
@Override
public String getValue() {
return orig.getValue();
}
}
public static void test(Original... o) {
if (o != null && o.length > 0) {
for (int i = 0; i < o.length; i++) {
if (o[i] instanceof Wrapper) {
o[i] = ((Wrapper) o[i]).orig; // Throws java.lang.ArrayStoreException at runtime
}
}
}
}
public static void main(String[] args){
test(new Wrapper[] { // Explicitly create an array of subclass type
new Wrapper(new Original())
});
}
This example gives no warnings or errors at compile-time. It seems like the compiler decides that an Wrapper[]
contains Wrapper
instances, which effectively means that those are definitely instances of Original
class. This is perfectly fine.
However, at runtime, the Wrapper[]
instance is directly passed into the method. I have thought that it would be smart enough to tear down this array and re-create an instance of Original[]
at runtime, but it seems like this is not the case.
Is this behavior ever documented somewhere (like JLS)? An ordinary programmer like me will always assume that I can manipulate that vararg parameter of Original...
as if it is an Original[]
.