您的位置:首页 > 其它

使用类加载器加载配置文件

2010-12-17 08:38 531 查看
package com.wangweijun;
import java.io.InputStream;
import java.util.Collection;
import java.util.Properties;
public class ClassLoaderTest {

/**
* 使用类加载器和Properties对象来加载属性文件和配置文件
*/
public static void main(String[] args) throws Exception{
InputStream in = ClassLoaderTest.class.getClassLoader()
.getResourceAsStream("com/wangweijun/cfg.properties");
Properties p = new Properties();
p.load(in);
in.close();
String className = (String)p.get("className");
Collection c = (Collection)Class.forName(className).newInstance();
//Collection c = new HashSet();
ReflectPoint p1 = new ReflectPoint(3, 3);
ReflectPoint p2 = new ReflectPoint(4, 4);
ReflectPoint p4 = new ReflectPoint(3, 3);
c.add(p1);
c.add(p2);
c.add(p4);
System.out.println(c.size());
System.out.println(c.size());
}
}

package com.wangweijun;

public class ReflectPoint {

public int x;
private int y;

public ReflectPoint(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;
ReflectPoint other = (ReflectPoint) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
}

cfg.properties属性文件的内容,且存于com/wangweijun这个包下,注意路劲问题

className=java.util.HashSet
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: