- import java.util.*;
- import java.lang.reflect.*;
- class Test
- {
- public static void main(String[] args)
- {
- ArrayList<String> list = new ArrayList<String>();
- try
- {
- Method addMethod=list.getClass().getMethod("add", String.class);
- //这里的String.class会报告NoSuchMethodException,
- //为什么?泛型已定义好为String类型了啊
- addMethod.invoke(list, "zhangsan");
- addMethod.invoke(list, "lisi");
- System.out.println(list);
- }
- catch (NoSuchMethodException e)
- {
- e.printStackTrace();
- }
- catch(SecurityException e)
- {
- e.printStackTrace();
- }
- catch (IllegalAccessException e)
- {
- e.printStackTrace();
- }
- catch (IllegalArgumentException e)
- {
- e.printStackTrace();
- }
- catch (InvocationTargetException e)
- {
- e.printStackTrace();
- }
- }
- }
复制代码 |
|