实现
最近突发奇想,java使用properties时每次都要调用getProperty方法获取配置信息,有时还要转换类型,这有点不方便,于是就自己实现了一个从properties到类的映射功能,方便读取配置信息。实现原理非常简单,利用java的反射功能找到类的所有公共字段,然后利用字段名作为key从properties中查找value,再将value转换为字段对应的类型。注意,类字段必须为public,且字段名必须与配置key一致,类无需getter\setter,因为字段都是public
/**
* 通过反射实现properties到java类文件的映射,目前支持类型:boolean,byte,short,int,float,double,long,string,
* java bean字段名必须与properties配置key一致,且必须为public
* @author lhl
*
* 2015年7月7日下午2:54:50
*/
public class ConfigParser
{
/**
* 从类路径加载配置并映射到类
* @param file
* @param clas
* @throws IllegalStateException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws IOException
*/
public static void parseFromClassPath(String file, Class<?> clas) throws IllegalStateException, IllegalArgumentException, IllegalAccessException, IOException
{
Properties prop = loadFromClassPath(file);
assignment(clas, prop);
}
/**
* 从类路径加载配置
* @param file
* @return
* @throws IOException
*/
private static Properties loadFromClassPath(String file) throws IOException
{
Properties prop = new Properties();
try (InputStream inStream = ConfigParser.class.getClassLoader().getResourceAsStream(file))
{
prop.load(inStream);
}
return prop;
}
/**
* 给字段赋值
* @param obj
* @param prop
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
private static void assignment(Class<?> obj, Properties prop) throws IllegalArgumentException, IllegalAccessException
{
Field[] allFields = obj.getFields();
for (Field field : allFields)
{
Class<?> type = field.getType();
String fieldName = field.getName();
String value = prop.getProperty(fieldName);
if (type == boolean.class)
{
field.setBoolean(obj, Boolean.parseBoolean(value));
}
else if (type == byte.class)
{
field.setByte(obj, Byte.parseByte(value));
}
else if (type == short.class)
{
field.setShort(obj, Short.parseShort(value));
}
else if (type == int.class)
{
field.setInt(obj, Integer.parseInt(value));
}
else if (type == float.class)
{
field.setFloat(obj, Float.parseFloat(value));
}
else if (type == double.class)
{
field.setDouble(obj, Double.parseDouble(value));
}
else if (type == long.class)
{
field.setLong(obj, Long.parseLong(value));
}
else if (type == String.class)
{
field.set(obj, value);
}
}
}
}
测试类:
/**
* @author lhl
*
* 2015年7月30日下午5:53:13
*/
public class TestConfig
{
public static String fieldA;
public static byte fieldB;
public static short fieldC;
public static int fieldD;
public static boolean fieldE;
public static float fieldF;
public static double fieldG;
public static long fieldH;
}
测试配置文件app.properties:
fieldA=this is first field
fieldB=2
fieldC=3
fieldD=4
fieldE=true
fieldF=5
fieldG=6
fieldH=7
使用方法:
ConfigParser.parseFromClassPath("app.properties", TestConfig.class);