本帖最后由 黑马_位志国 于 2013-4-2 22:38 编辑
import java.io.*;
import java.util.*;
//通过反射加载配置文件
public class ReflectTest2 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
InputStream in = null;
try {
//in = new FileInputStream("config.properties");//此文件存放在该project下。
in = ReflectTest2.class.getClassLoader().getResourceAsStream("config.properties");
Properties props = new Properties();
props.load(in);
String className = props.getProperty("className");
Collection<ReflectPoint> collections = (Collection)Class.forName(className).newInstance();
//Collection collections = new HashSet();
ReflectPoint rp1 = new ReflectPoint(3, 3);
ReflectPoint rp2 = new ReflectPoint(5, 5);
ReflectPoint rp3 = new ReflectPoint(3, 3);
collections.add(rp1);
collections.add(rp2);
collections.add(rp3);
collections.add(rp1);
System.out.println(collections.size());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
if(in != null)
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
config.properties文件内容是:
className = java.util.HashSet
为什么运行该类会发生如下异常:
Exception in thread "main" java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Unknown Source)
at java.util.Properties.load0(Unknown Source)
at java.util.Properties.load(Unknown Source)
at com.ijunfu.study.java.enhance.day01.ReflectTest2.main(ReflectTest2.java:19)
|