通过反射获取list集合的所有方法,然后把字符串存入集合中。
import java.lang.reflect.InvocationTargetException;
public class reflectDemo {
public static void main(String[] args) throws NoSuchMethodException,
NoSuchMethodException, InvocationTargetException,
InvocationTargetException, IllegalAccessException {
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 6; i++) {
list.add(i);
}
String str = "我是字符串";
Method method = list.getClass().getMethod("add", Object.class);
method.invoke(list, str);
Iterator<Integer> iterator = list.iterator();
while (iterator.hasNext()) {
System.out.print(iterator.next()+" ");
}
}
}
输出结果:
0 1 2 3 4 5 我是字符串