I was trying to implement some kind of custom serialization with reflection, and then I found out that you just cannot cast A[]
to B[]
if A isn't a subtype of B even if all the elements in the array are subtypes of B (It should work because of type erasing because at the end of the day both a[]
and b[]
are Object[]
).
here is an example of what I mean:
public class Foo {
public static void main(String[] args) throws Exception {
new Foo().testGenerics();
}
public LinkedList<String> strList;
public String[] strArr;
public void testGenerics() throws Exception {
LinkedList<Object> objList = new LinkedList<Object>();
objList.add("foo");
Object[] objArr = new Object[1];
objArr[0] = "bar";
Foo.class.getField("strList").set(this, objList);
System.out.println("list[0] = " + strList.get(0));
System.out.println("list len = " + strList.size());
Foo.class.getField("strArr").set(this, objArr);
System.out.println("arr[0] = " + strArr[0]);
System.out.println("arr len = " + strArr.length);
}
}
In this example the list works fine but the array throws an exception at the line that tries to set it.
is there any reason arrays ignore type erasing, and is there any good way to create an array and a list for a given type at runtime?
Aucun commentaire:
Enregistrer un commentaire