错误方式
下面方式会报错 Cannot create a generic array of T:
T[] array = new T[];
正确方式
通过反射创建:
import java.lang.reflect.Array;
class ArrayUtil {
@SuppressWarnings({ "unchecked", "hiding" })
public static <T> T[] newArray(Class<T> type,int length) {
return (T[]) Array.newInstance(type, length);
}
}
使用:
Person[] persons = new ArrayUtil().newArray(Person.class, 10);
参考:
https://www.cnblogs.com/minghaiJ/p/11259318.html
https://blog.csdn.net/weixin_43821874/article/details/92793059