博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用反射在 ArrayList<Integer> 集合中添加一个字符串数据;
阅读量:4136 次
发布时间:2019-05-25

本文共 1018 字,大约阅读时间需要 3 分钟。

整体思路就是:

1:新建一个ArrayList<integer>集合

2:然后使用反射,返回ArrayList的class对象

3:使用class中的getmethod方法,找到ArrayList中的   add方法(此方法是添加元素的时候用的)

3:使用method类中的invoke方法,将字符串添加到集合中

4:遍历集合 输出字符串。

//导包import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.util.ArrayList;/** * 使用反射在 ArrayList
这个集合中添加一个字符串数据; * * @author Starry */public class ArrayListStringDemo { // 主程序入口 public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { // 定义一个ArrayList集合 泛型类型为Integer ArrayList
arl = new ArrayList
(); arl.add(3); // 将上面定义的Arraylist 返回Arraylist的class对象 Class
clazz = arl.getClass(); // 获取Arraylist 类里面的add方法 Method method = clazz.getMethod("add", Object.class); // 对arl对象调用由 Method 对象表示的底层方法 ,向集合中添加字符串 method.invoke(arl, "这是一个字符串"); method.invoke(arl, "这是两个字符串"); // 方法1:使用增强for来循环输出 集合中的数据 for (Object item : arl) { System.out.println(item); } }}

转载地址:http://asxvi.baihongyu.com/

你可能感兴趣的文章
MySQL字段类型的选择与MySQL的查询效率
查看>>
Java的Properties配置文件用法【续】
查看>>
JAVA操作properties文件的代码实例
查看>>
IPS开发手记【一】
查看>>
Java通用字符处理类
查看>>
文件上传时生成“日期+随机数”式文件名前缀的Java代码
查看>>
Java代码检查工具Checkstyle常见输出结果
查看>>
北京十大情人分手圣地
查看>>
Android自动关机代码
查看>>
Android中启动其他Activity并返回结果
查看>>
2009年33所高校被暂停或被限制招生
查看>>
GlassFish 部署及应用入门
查看>>
iWatch报错: Authorization request cancled
查看>>
iWatch报错: Authorizationsession time out
查看>>
X-code7 beta error: warning: Is a directory
查看>>
Error: An App ID with identifier "*****" is not avaliable. Please enter a different string.
查看>>
X-code beta 开发iWatch项目,运行没有错误,但是某些操作一点就崩,而且找不错误的原因场景一
查看>>
Xcode 报错: Extra argument in call
查看>>
iTunes Connect 上传APP报错: Communication error. please use diagnostic mode to check connectivity.
查看>>
#import <Cocoa/Cocoa.h> 报错 Lexical or Preprocessor Issue 'Cocoa/Cocoa.h' file not found
查看>>