A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 蓝墨清幽 中级黑马   /  2015-4-22 11:01  /  342 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. package com.itheima;


  2. import java.lang.reflect.Method;
  3. import java.util.ArrayList;


  4. public class Test11 {

  5.         /**
  6.          * 1. 题目:ArrayList<Integer> list = new ArrayList<Integer>();
  7.          * 在这个泛型为Integer的ArrayList中存放一个String类型的对象。 分析:
  8.          *  1.定义Integer泛型
  9.          *  2.取得list的所有方法
  10.          * 3.遍历打印list的方法
  11.          * 4.通过反射来执行list的第一个方法,第一个是list对象,代表该对象的方法,第二个是方法参数 步骤:
  12.          */
  13.         public static void main(String[] args) {
  14.                
  15.                 //创建Arraylist
  16.                 ArrayList<Integer> list = new ArrayList<Integer>();
  17.                
  18.                 /**获得list的类的字节码(Class)对象,并获得方法数组Mathod[ ]
  19.                  * 获得Method的数组中的Method方法顺序与自己定义方法的顺序无关
  20.                  * 数组中Method的顺序按照方法名首字母顺序排列
  21.                  */
  22.                 Method[ ] methods = list.getClass().getMethods();
  23.                
  24.                 //遍历Method[ ]
  25.                 System.out.println(methods.length);
  26.                 for(int i=0; i<methods.length; i++){
  27.                         System.out.println(methods[i].getName().toString());
  28.                 }
  29.                
  30.                 try {
  31.                         /**通过Method对象,调用Arraylist中的方法(即通过反射调用)
  32.                          * 从Methods[ ]数组中取Method的方式不常用
  33.                          */
  34.                         methods[0].invoke(list, "String");
  35.                        
  36.                         /**直接调用某个确定的方法经常使用getMethod
  37.                         *第一个参数 方法名称(String)
  38.                         *第二个参数 方法的参数列表;如果参数有多个,有顺序,
  39.                         *不用数组封装,继续用逗号,写下一个参数
  40.                         **/
  41.                         Method method = list.getClass().getMethod("get", int.class);
  42.                        
  43.                         /**获取Method方法后,调用invoke方法进行调用
  44.                         *第一个参数 所要调用这个Method方法的对象
  45.                         *第二个及后续参数  给这个方法传递的参数
  46.                         *返回值 为Object,可以强制转化
  47.                         **/
  48.                         Object obj = method.invoke(list, 0);
  49.                        
  50.                         /**
  51.                          * 输出
  52.                          */
  53.                         System.out.println("结果="+obj.toString());
  54.                 } catch (Exception e) {
  55.                         // TODO Auto-generated catch block
  56.                         e.printStackTrace();
  57.                 }
  58.         }
  59.        
  60. }
复制代码


2 个回复

倒序浏览
高人啊,真是好东西啊!!
回复 使用道具 举报
这个还不错,好帖子,大家谈谈
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马