【文件属性】:
文件名称:java解析Properties配置文件为对象Bean
文件大小:1KB
文件格式:RAR
更新时间:2023-08-10 09:42:53
properties bean
利用java的反射解析Properties文件转成对象
/**
* 解析properties文件为对象
* @param
* @param propPath
* @param cls
* @return
* @throws InstantiationException
* @throws IllegalAccessException
* @throws IOException
*/
public static T paseObject(String propPath, Class cls)
throws InstantiationException, IllegalAccessException, IOException {
Properties prop = getConfigProperties(propPath);
T obj = cls.newInstance();
Field[] fList = obj.getClass().getDeclaredFields();
for (Field field : fList) {
String value = prop.getProperty(field.getName());
String typeName = field.getType().getTypeName();
System.out.println(value);
System.out.println(typeName);
if (value != null) {
value = value.trim();
if(typeName.equals("java.lang.String")) {
field.set(obj, value);
}else if(typeName.equals("int")) {
field.setInt(obj, Integer.parseInt(value));
}else if(typeName.equals("float")) {
field.setFloat(obj, Float.parseFloat(value));
}else if(typeName.equals("double")) {
field.setDouble(obj, Double.parseDouble(value));
}else if(typeName.equals("long")) {
field.setLong(obj, Long.parseLong(value));
}else if(typeName.equals("boolean")) {
field.setBoolean(obj, Boolean.parseBoolean(value));
}else if(typeName.equals("byte")) {
field.setByte(obj, Byte.parseByte(value));
}else if(typeName.equals("short")) {
field.setShort(obj, Short.parseShort(value));
}
}
}
return obj;
}
【文件预览】:
ConfigLoader.java
ConfObj.java