泛型数组
-
可以声明带泛型的数组引用,但是不能直接创建带泛型的数组对象
image.png
- 可以通过java.lang.reflect.Array的newInstance(Class<T>,int) 创建T[]数组
public class Fruit<T> {
private T[] arr;
public Fruit(Class<T>clz, int length) {
// 通过Array.newInstance创建泛型数组
arr = (T[]) Array.newInstance(clz, length);
}
// 填充数组
public void put(int index, T t) {
arr[index] = t;
}
public T get(int index) {
return arr[index];
}
public T[] getArr() {
return arr;
}
public static void main(String[] args) {
Fruit<String> fruit = new Fruit<>(String.class, 3);
fruit.put(0, "香蕉");
fruit.put(1, "火龙果");
fruit.put(2, "桃子");
System.out.println(Arrays.toString(fruit.getArr()));
}
}
可变参数
- 在指定类型后面加 ...
- 一个方法中只能指定一个可变参数,并且可变参数必须是方法的最后一个参数
public static void printNum(int a, double ... num) {
System.out.println(a);
for (int i = 0; i < num.length; i++) {
System.out.println(num[i]);
}
}
反射获取泛型信息
public class Generic {
public void print(Map<String, User> map, List<User> list) {
}
public Map<String,User> getOne() {return null;}
public static void main(String[] args) throws NoSuchMethodException, SecurityException {
Method printMethod = Generic.class.getDeclaredMethod("print", Map.class, List.class);
Type[] types= printMethod.getGenericParameterTypes();
for (Type type : types) {
System.out.println(type.getTypeName());
if (type instanceof ParameterizedType) {
Type[] types2 = ((ParameterizedType) type).getActualTypeArguments();
for (Type type2 : types2) {
System.out.println(type2);
}
}
}
System.out.println("===============");
Method getOneMethod = Generic.class.getDeclaredMethod("getOne");
Type type3= getOneMethod.getGenericReturnType();
if (type3 instanceof ParameterizedType) {
Type[] types2 = ((ParameterizedType) type3).getActualTypeArguments();
for (Type type2 : types2) {
System.out.println(type2);
}
}
}
}
网友评论