问题:ArrayList<Integer>的对象如何添加一个字符串数据?
解决办法:泛型是在编译时期检查的,但是在运行期会被擦除掉
package com.wrb.ref;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
public abstract class Demo1 {
/**
* @param args
* @throws ClassNotFoundException
* @throws NoSuchMethodException
* @throws SecurityException
* @throws InvocationTargetException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public static void main(String[] args) {
try {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
//添加字符串
Class<?> clazz = Class.forName("java.util.ArrayList");
//获取ArrayList的add()方法
Method add = clazz.getMethod("add", Object.class);
//添加要添加的字符串
add.invoke(list, "要添加的字符串");
System.out.println(list);
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
打印结果:
完成!!能帮助到你的就点赞或者好评吧,谢谢!