利用反射模拟框架
!注意路径,实际应用时使用getRealPath()+程序内路径 _运算完整的路径
或者使用类加载器加载文件,但是使用类加载器是只读的。
类加载器
InputSream in = TestFramework.class.getClassLoader().getResourceAsStream(包路径+文件名)
或者:InputSream in = TestFramework.getResourceAsStream(相对自身包的路径+文件名)
config.properties:
className=java.util.HashSet
import java.io.*;
import java.util.*;
public class TestFramework {
public static void main(String[] args) {
InputStream in = null;
try {
in = new FileInputStream("config.properties");
} catch (FileNotFoundException e) {
System.out.println("文件未找到。");
e.printStackTrace();
}
Properties prop = new Properties();
try {
prop.load(in);
} catch (IOException e) {
System.out.println("载入文件出现错误。");
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
System.out.println("文件读取结束出错。");
e.printStackTrace();
}
String className = prop.getProperty("className");
Collection collection = null;
try {
collection = (Collection)Class.forName(className).newInstance();
} catch (Exception e) {
System.out.println("创建对象失败");
e.printStackTrace();
}
Point p1 = new Point(1,1);
Point p2 = new Point(2,2);
Point p3 = new Point(1,1);
Point p4 = new Point(3,3);
collection.add(p1);
collection.add(p2);
collection.add(p3);
collection.add(p4);
System.out.println(collection.size());
}
}
public class Point {
int x ;
int y ;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}
@Override
public 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;
}
}