本帖最后由 yedong07a 于 2013-5-11 11:45 编辑
配置文件config.properties的内容:className=java.util.HashSet
public class ReflectTest2 {
public static void main(String[] args) throws Exception {
InputStream ips = ReflectTest2.class.getResourceAsStream("/cn/itcast/day1/resources/config.properties");
Properties props = new Properties();
props.load(ips);
ips.close();
String className = props.getProperty("className");
Collection collections = (Collection) Class.forName(className).newInstance();
ReflectPoint pt1 = new ReflectPoint(3, 3);
ReflectPoint pt2 = new ReflectPoint(5, 5);
ReflectPoint pt3 = new ReflectPoint(3, 3);
collections.add(pt1);
collections.add(pt2);
collections.add(pt3);
collections.add(pt1);
System.out.println(collections.size());
}
}
加载Properties 文件,Class.forName得到类,newInstance调用不带无参的构造方法。
public class ReflectPoint {
private int x;
private int y;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public ReflectPoint(int x, int y) {
super();
this.x = x;
this.y = y;
}
}
把程序要调用的类,不显示具体类的名字,而使用配置文件。
|
|