黑马程序员技术交流社区

标题: 反射怎么和怎么和具体的类对象联系起来 [打印本页]

作者: crazy_primitive    时间: 2013-7-18 01:55
标题: 反射怎么和怎么和具体的类对象联系起来
本帖最后由 crazy_primitive 于 2013-7-18 13:13 编辑
  1. public class ReflectTest2 {
  2.         public static void main(String[] args) throws Exception{
  3.                 // TODO Auto-generated method stub
  4.                 InputStream ips = new FileInputStream("config.properties");//将配置文件读取到流中
  5.                 Properties props = new Properties();
  6.                 props.load(ips);//将流中的配置文件加载进来
  7.                 ips.close();
  8.                 String className = props.getProperty("className");
  9.                 Collection collections = (Collection) Class.forName(className).newInstance();
  10.                 //这里是怎么和ReflectPoint类的对象联系起来的?
  11.                 ReflectPoint rpt1 = new ReflectPoint(4,5);
  12.                 ReflectPoint rpt2 = new ReflectPoint(7,2);
  13.                 ReflectPoint rpt3 = new ReflectPoint(4,5);
  14.                 collections.add(rpt1);
  15.                 collections.add(rpt2);
  16.                 collections.add(rpt3);
  17.                 collections.add(rpt1);
  18.                 System.out.println(collections.size());
  19.         }
  20. }
复制代码

作者: 王靖远    时间: 2013-7-18 08:03
将ReflectPoint类的对象作为集合元素存入通过反射创建的集合中。
作者: mk7    时间: 2013-7-18 08:53
Collection collections = (Collection) Class.forName(className).newInstance();
这行代码就已经利用反射创建了集合的实例对象,集合的具体类型是根据配置文件中的
className确定的,然后将创建的ReflectPoint实例对象装入集合中,这不就联系起来了吗




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2