Inclusion into the problem with generics and array types that I cannot solve. It comes down to that. In the following code, how can I convert a general list to an array of the same generic type using the factory ("T convert (String value)") method to convert each individual element of an input shared list:
@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) {
As you can see, my naive approach was to simply use the toArray method and make the result as follows:
(T) value.toArray()
but this throws a ClassCastException:
java.lang.ClassCastException: [Ljava.lang.Object; cannot be applied to [Ljava.lang.Integer
Is there a way to solve this problem that I do not see, or should I use a different approach?
Edit
Here is the specific code I'm trying to fix. In particular, the visitArray () method:
https://github.com/johncarl81/transfuse/blob/master/transfuse/src/main/java/org/androidtransfuse/analysis/adapter/AnnotationTypeValueConverterVisitor.java
source share