黑马程序员技术交流社区

标题: 反射练习:写一个小框架 [打印本页]

作者: jiaweizhang    时间: 2015-9-23 09:49
标题: 反射练习:写一个小框架
反射练习:写一个小框架,源代码不用更改,更改配置文件的集合属性,返回不同的运行效果

config.properties 文件定义的属性
className = java.util.HashSet        <!--   />


package ReflectionFrame;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Collection;
import java.util.Properties;


public class ReflectionFrameTest {
        public static void main(String[] args) {
                /**
                 * 使用反射,写一个小框架例子
                 * 读取配置文件,配置文件可以更改不同类型的集合,而源代码不需要更改,
                 */
                try {
                        //通过打开一个到实际文件的连接来创建一个 FileInputStream
                        InputStream ips = new FileInputStream("config.properties");
                        Properties p = new Properties(); //创建Properties对象加载流中的数据
                        p.load(ips);        //加载配置文件
                        ips.close();        //关闭流资源
                        String className = p.getProperty("className");        //读取配置文件中指定的属性
                        Collection collations = (Collection)Class.forName(className).newInstance(); //根据className属性返回不同的集合对象
                        PointDemo pd1  = new PointDemo(2, 5);
                        PointDemo pd2  = new PointDemo(4, 3);
                        PointDemo pd3  = new PointDemo(1, 6);
                       
                        collations.add(pd1);
                        collations.add(pd2);
                        collations.add(pd3);
                        collations.add(pd1);
                       
                        System.out.println(collations.size());                //通过更改配置文件中className属性的值,Hashset或ArrayList ,会出现不同的效果
                       
                } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
        }
}

class PointDemo{
        int x;
        int y;
        public PointDemo(int x, int y) {
                super();
                this.x = x;
                this.y = y;
        }
       
}
作者: fmi110    时间: 2015-9-23 10:10
学习了 支持一下




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