反射模拟框架中配置的加载

来源:互联网 发布:狗粮 饼干 淘宝 编辑:程序博客网 时间:2024/06/05 17:30

test.java


package test2;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.util.Collection;import java.util.Properties;/** *  * @author Dqd * 模拟框架中配置的加载 * 在源文件中不出现具体的容器名称,通过配置文件来配置 * */public class test {public static void main(String[] args) throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException {//首先加载properties文件//InputStream ip = new FileInputStream("config.properties");//或者使用类加载器加载InputStream ip = test.class.getClassLoader().getResourceAsStream("test2/config.properties");//或者省略.getClassLoader().那么后面的括号内就不用写包名了,因为这是相对当前包而言的//如果路径的开头是/,代表从跟开始进行寻找Properties pro = new Properties();pro.load(ip);ip.close();String className = pro.getProperty("className");Collection coll = (Collection) Class.forName(className).newInstance(); Point p1 = new Point(1,1);Point p2 = new Point(2,2);Point p3 = new Point(3,3);Point p4 = new Point(1,1);coll.add(p1);coll.add(p2);coll.add(p3);coll.add(p4);System.out.println(coll.size());}}


config.properties:

className=java.util.HashSetclassName2=java.util.ArrayList

Point:


package test2;public class Point {private int x;private int y;public Point(int x, int y) {this.x = x;this.y = y;}@Overridepublic int hashCode() {final int prime = 31;int result = 1;result = prime * result + x;result = prime * result + y;return result;}@Overridepublic boolean equals(Object obj) {if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;Point other = (Point) obj;if (x != other.x)return false;if (y != other.y)return false;return true;}}





0 0
原创粉丝点击