1.读取配置文件,配置文件的命名需与类名相同,也可以写死,但要与类在同一目录下。
public class MyProperties extends Properties {
private static final long serialVersionUID = -2189089546796878893L;
public MyProperties(@SuppressWarnings("rawtypes") Class clazz) throws IOException {
String invokeClassShortName = clazz.getSimpleName();
String propertiesFileName = invokeClassShortName + ".properties";
InputStreamReader reader = new InputStreamReader(clazz.getResourceAsStream(propertiesFileName));
this.load(reader);
}
public String getString(String key) {
Object obj = getProperty(key);
return (String)obj;
}
}
2抽象类 调用方继承该抽象类
public abstract class PropertiesUtils4Test {
protected MyProperties rb;
public PropertiesUtil(){
String className = this.getClass().getName();
try {
rb = new MyProperties(getClass());
} catch (Exception mre) {
System.out.println("No resource bundle found for: " + className);
}
}
//利用java反射原理,将配置文件的值复制到对象中
protected void populate() {
if (rb == null) return ;
try {
BeanUtils.copyProperties(this, rb);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
3.`使用时继承PropertiesUtil 类
public class TestProperies extends PropertiesUtils4Test {
@Test
public void testStart() throws Exception
{
String id= rb.getString("flowNoForCommit");
System.out.println(id);
testEntity t = new testEntity();
t.load();
System.out.println(t.toString());
}
}
4.测试用java反射的实体类
public class testEntity extends PropertiesUtils4Test{
public String productNoForInit;
public String getProductNoForInit() {
return productNoForInit;
}
public void setProductNoForInit(String productNoForInit) {
this.productNoForInit = productNoForInit;
}
@Override
public String toString() {
return "testEntity [productNoForInit=" + productNoForInit + "]";
}
public void load() {
super.populate();
}
}