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

全部博文(164)

文章存档

2017年(2)

2015年(67)

2014年(95)

我的朋友

分类: Java

2014-11-23 12:10:12

要想通过反射构造出一个类的实例,需要经过以下步骤:
1 反射出该类的构造函数
2 通过该构造函数创建对象
例如,反射出类String 构造方法new 出的对象
( buffer) 
          分配一个新的字符串,它包含字符串缓冲区参数中当前包含的字符序列。

点击(此处)折叠或打开

  1. //new String(new StringBuffer("abc"));
  2. Constructor constructor = String.class.getConstructor(StringBuffer.class);
  3. String str = (String)constructor.newInstance(new StringBuffer("abc"));
  4. System.out.println(str.charAt(1));



点击(此处)折叠或打开

  1. /*
  2.  * 通过反射获取构造方法并使用。
  3.  */
  4. public class ReflectDemo {
  5.     public static void main(String[] args) throws Exception {
  6.         // 获取字节码文件对象

  7.         Class c = Class.forName("com.lhk.Person");

  8.         // 获取构造方法

  9.         // public Constructor[] getConstructors():所有公共构造方法

  10.         // public Constructor[] getDeclaredConstructors():所有构造方法

  11.         // Constructor[] cons = c.getDeclaredConstructors();

  12.         // for (Constructor con : cons) {

  13.         // System.out.println(con);

  14.         // }


  15.         // 获取单个构造方法

  16.         // public Constructor getConstructor(Class... parameterTypes)

  17.         // 参数表示的是:你要获取的构造方法的构造参数个数及数据类型的class字节码文件对象

  18.         Constructor con = c.getConstructor();// 返回的是构造方法对象


  19.         // Person p = new Person();

  20.         // System.out.println(p);

  21.         // public T newInstance(Object... initargs)

  22.         // 使用此 Constructor 对象表示的构造方法来创建该构造方法的声明类的新实例,并用指定的初始化参数初始化该实例。

  23.         Object obj = con.newInstance();
  24.         System.out.println(obj);
  25.         
  26.         // Person p = (Person)obj;

  27.         // p.show();

  28.     }
  29. }






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