遇到了我无法解决的泛型和数组类型问题。归结到这一点。在下面的代码中,如何将通用列表转换为具有相同通用类型的数组,同时使用工厂方法(“T convert(String value)”)来转换输入通用列表中的每个单独元素:Java泛型和数组类型
@Test
public void test(){
List<String> integers = Arrays.asList("1", "2", "3", "4");
Integer[] integerArray = new TypeConverter<Integer[]>(Integer[].class).convert(integers);
assertEquals(4, integerArray.length);
assertEquals(1, integerArray[0].intValue());
assertEquals(2, integerArray[1].intValue());
assertEquals(3, integerArray[2].intValue());
assertEquals(4, integerArray[3].intValue());
}
public class TypeConverter<T>{
Class<T> type;
public TypeConverter(Class<T> type) {
this.type = type;
}
T convert(List<String> values){
List output = new ArrayList();
for (String value : values) {
//have to use Object.class here since I cant get the non-array type of T:
output.add(new TypeConverter(type.getComponentType()).convert(value));
}
return (T) output.toArray();
}
T convert(String value){
//convert to an int;
if(type == Integer.class){
return (T) new Integer(Integer.parseInt(value));
}
return null;
}
}
正如你看到的,我天真的做法是简单地使用指定者的方法,并把结果像这样:
(T) value.toArray()
但这会导致一个ClassCastException:
的java.lang .ClassCastException:[L java.lang.Object继承;不能投到[Ljava.lang.Integer
有没有办法解决这个问题,我没有看到,或者我应该采取另一种方法?
编辑
这里,我试图解决具体的代码。具体的visitArray()方法:
可能重复[?List类的指定者:Java的,为什么我不能的“整数”列表转换成“整数”阵列(HTTP://计算器.COM /问题/ 7281793 /列表班组长-指定者功能于Java的,为什么-着-I-转换-A-列表的整数到一个-INT) –
其实我提交我的职务之前阅读该文章。我的问题不是重复的,因为我在询问有关数组的泛型。 –