通过反射可以在ArrayList<Integer> list中存入String类型对象,为什么不可以再ArrayList<String> list中存入Integer类型的对象呢?
- package com.itheima;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.IOException;
- import java.lang.reflect.Field;
- import java.lang.reflect.InvocationTargetException;
- import java.lang.reflect.Method;
- import java.util.ArrayList;
- import java.util.Iterator;
- import java.util.List;
- import java.util.Properties;
- import java.util.Set;
- public class Test5{
-
- public static void main(String []args) throws IOException, ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, Exception{
-
-
- List<String> list = new ArrayList<String>();
- list.add("a");
- list.add("b");
- Class<?> cls = list.getClass();
- Method m =cls.getMethod("add", Object.class);
- m.setAccessible(true);
- m.invoke(list, new Integer(1));
- System.out.println(list.get(2));
-
-
-
-
-
-
-
- }
-
-
- }
复制代码
错误提示如下:Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String |
|