배열을 만들고 거기에 객체를 저장하려고하는 다음 코드가 있습니다. 런타임에는 ArrayStoreException
이 표시됩니다.제네릭 어레이 생성이 예상대로 작동하지 않는 이유는 무엇입니까?
import java.lang.reflect.Array;
public class GenericsArrayCreation<T> {
public static <T> void Test(T[] A){
@SuppressWarnings("unchecked")
T[] temp = (T[]) Array.newInstance(A.getClass(), A.length);
for(int i = 0;i<temp.length;i++){
temp[i] = A[i];
System.out.println(temp[i].toString());
}
}
public static void main(String[] args){
String[] strs = {"a", "b", "c"};
GenericsArrayCreation.Test(strs);
}
}
어떻게 든이 왜 잘못 때문에 문
T[] temp = (T[]) Array.newInstance(A.getClass(), A.length);
의 것을 이해? 런타임에 A.getClass()
은 String
을 반환하므로 temp
은 문자열 배열이어야합니다. 이 경우, temp[i] = A[i]
할당이 작동하지 않는 이유는 무엇입니까?
'A.getClass()'가'String'이라는 것을 (디버거 또는'print' 문에) 확인 했습니까? – chrylis