本帖最后由 刘军亭 于 2013-1-27 14:12 编辑
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Collection;
import java.util.Properties;
/*
* 反射的应用,微型框架
config.properties文件内容:className = java.util.HashSet
* */
public class ReflectTest {
public static void main(String[] args) throws Exception {
InputStream ips = new FileInputStream("config.properties");
Properties props = new Properties();
props.load(ips);
ips.close();
String className = props.getProperty("className");
//而这里也会new一个HashSet对象但为什么不用导包就可以正常运行呢。
Collection collections = (Collection)Class.forName(className).newInstance();
// 如果不用反射时候的普通做法。要导入相应的包。
//Collection collections = new HashSet();
ReflectPoint pt1 = new ReflectPoint(3,3);
ReflectPoint pt2 = new ReflectPoint(2,2);
ReflectPoint pt3 = new ReflectPoint(1,1);
collections.add(pt1);
collections.add(pt2);
collections.add(pt3);
collections.add(pt3);
System.out.println(collections.size());
}
}
class ReflectPoint{
int x;
int y;
ReflectPoint(int x,int y){
this.x = x;
this.y = y;
}
} |