Chinaunix首页 | 论坛 | 博客
  • 博客访问: 243142
  • 博文数量: 164
  • 博客积分: 60
  • 博客等级: 民兵
  • 技术积分: 1129
  • 用 户 组: 普通用户
  • 注册时间: 2010-07-09 21:55
文章分类

全部博文(164)

文章存档

2017年(2)

2015年(67)

2014年(95)

我的朋友

分类: Java

2015-04-29 15:27:35




点击(此处)折叠或打开

  1. public class ReflectDemo {
  2.     public static void main(String[] args) throws Exception {
  3.         // 获取字节码文件对象

  4.         Class c = Class.forName("cn.lhk.Person");

  5.         // 获取所有的方法

  6.         // Method[] methods = c.getMethods(); // 获取自己的包括父亲的公共方法

  7.         // Method[] methods = c.getDeclaredMethods(); // 获取自己的所有的方法

  8.         // for (Method method : methods) {

  9.         // System.out.println(method);

  10.         // }


  11.         Constructor con = c.getConstructor();
  12.         Object obj = con.newInstance();

  13.         /*
  14.          * Person p = new Person(); p.show();
  15.          */

  16.         // 获取单个方法并使用

  17.         // public void show()

  18.         // public Method getMethod(String name,Class... parameterTypes)

  19.         // 第一个参数表示的方法名,第二个参数表示的是方法的参数的class类型

  20.         Method m1 = c.getMethod("show");
  21.         // obj.m1(); // 错误

  22.         // public Object invoke(Object obj,Object... args)

  23.         // 返回值是Object接收,第一个参数表示对象是谁,第二参数表示调用该方法的实际参数

  24.         m1.invoke(obj); // 调用obj对象的m1方法


  25.         System.out.println("----------");
  26.         // public void method(String s)

  27.         Method m2 = c.getMethod("method", String.class);
  28.         m2.invoke(obj, "hello");
  29.         System.out.println("----------");

  30.         // public String getString(String s, int i)

  31.         Method m3 = c.getMethod("getString", String.class, int.class);
  32.         Object objString = m3.invoke(obj, "hello", 100);
  33.         System.out.println(objString);
  34.         // String s = (String)m3.invoke(obj, "hello",100);

  35.         // System.out.println(s);

  36.         System.out.println("----------");

  37.         // private void function()

  38.         Method m4 = c.getDeclaredMethod("function");
  39.         m4.setAccessible(true);
  40.         m4.invoke(obj);
  41.     }
  42. }

阅读(1014) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~