我设计了一个泛型方法,使数组更改类型后返回
结果显示异常:class [Ljava.lang.Object; cannot be cast to class [Ljava.lang.Integer;
实际上返回的是Object[]类型,请问应该如何改正?
测试代码:
String[] cs3 = new String[] { "123", "321" };
Integer[] cs3s = convert(cs3, Integer[].class);
System.out.println(Arrays.toString(cs3s));
List<Boolean> list4 = new ArrayList<>();
list4.add(true);
list4.add(false);
Boolean[] list4s = convert(list4, Boolean[].class);
System.out.println(Arrays.toString(list4s));
方法代码:
public static <T> T convert(@NotNull Object obj, Class<T> itemClass) {
if (obj.getClass() == itemClass) return (T) obj;
String itemClassName = itemClass.getName();
if (itemClassName.startsWith("[")) {
if (itemClassName.charAt(1) == 'L') {
try {
Class<?> clazz = Class.forName(itemClassName.substring(2, itemClassName.length() - 1));
Constructor<?> type = getConstructor(clazz, "java.lang.String");
if (type == null) throw new TypeException("不支持的转换类型");
if (obj instanceof Collection) {
List<Object> list = ((List<Object>) obj);
// Object[] result = new Object[list.size()];
for (int i = 0; i < list.size(); i++) {
list.set(i, type.newInstance(String.valueOf(list.get(i))));
}
return (T) list.toArray();
} else {
Object[] objs = ((Object[]) obj);
Object[] result = new Object[objs.length];
for (int i = 0; i < objs.length; i++) {
result[i] = type.newInstance(String.valueOf(objs[i]));
}
return (T) result;
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
}
} else if (itemClassName.charAt(1) == '[') {
throw new TypeException("不支持一维以上数组转换类型");
} else {
throw new TypeException("不支持基元类型转换");
}
} else {
throw new TypeException("测试用,仅支持一维度数组");
}
}
public static Constructor<?> getConstructor(@NotNull Class<?> itemClass, @NotNull String item) {
Constructor<?> type = null;
for (var con : itemClass.getConstructors()) {
Class<?>[] parameterTypes = con.getParameterTypes();
if (parameterTypes.length == 1 && parameterTypes[0].getName().equals("java.lang.String")) {
type = con;
}
}
return type;
}