- 首先创建一个javabean实体
//实体类---javaBean
public class Person {
public int id;
public String name;
public Person(int id, String name) {
super();
this.id = id;
this.name = name;
}
public Person(){}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "编号:"+ this.id+" 姓名:"+ this.name;
}
}
2.按自己的意愿对配置文件(a.txt)进行格式上的要求,只要和解析相对应即可
com.introspector.Person
id=12
name=ss
3.利用反射机制获取对象并解析内容
public class Demo {
public static void main(String[] args) throws Exception {
Person p = (Person)getInstance();
System.out.println(p);
}
public static Object getInstance() throws Exception {
BufferedReader bufferedReader = new BufferedReader(new FileReader("a.txt"));
//读取配置文件完整类名
String className = bufferedReader.readLine();
//通过class对象名获取Class对象
Class clazz = Class.forName(className);
//通过class对象获取无参构造函数
Constructor constructor = clazz.getConstructor(null);
//创建对象
Object o = constructor.newInstance(null);
String line = null;
while((line = bufferedReader.readLine())!=null){
String[] datas = line.split("=");
Field field = clazz.getDeclaredField(datas[0]);
if(field.getType()==int.class){
field.set(o, Integer.parseInt(datas[1]));
}else{
field.set(o, datas[1]);
}
}
return o;
}
}
配置文件基本思想的简单实现,主要应用到java中的IO流操作,javabean以及反射机制
执行结果如下: