- import java.lang.reflect.*;
- import java.util.ArrayList;
- import java.util.List;
- public class Demo
- {
- public static void main(String[] args) throws Exception
- {
- List<String> list = new ArrayList<String>();
- //通过反射向集合里添加Integer类型数据
- list.getClass().getMethod("add", Object.class).invoke(list,'a');
- System.out.println(list.size());//1
- Object obj = list.get(0);
- System.out.println(obj); //1
- }
- }
复制代码
但是
- import java.lang.reflect.*;
- import java.util.ArrayList;
- import java.util.List;
- public class Demo
- {
- public static void main(String[] args) throws Exception
- {
- List<String> list = new ArrayList<String>();
- //通过反射向集合里添加Integer类型数据
- list.getClass().getMethod("add", Object.class).invoke(list,'a');
- System.out.println(list.size());//1
- //Object obj = list.get(0);
- System.out.println(list.get(0));
- //Exception in thread "main" java.lang.ClassCastException: java.lang.Character can
- //not be cast to java.lang.String
- }
- }
复制代码
为什么? |