Java-读取properties配置文件反射对类属性赋值
背景:
Java一般的类属性赋值方式是:通过读取或者外部传入的参数,然后调用属性的set方法进行赋值
这种方法,每次修改模板类,就需要修改所有对类操作赋值的方法
解决思路:
是否可以通过设定默认规则由一个通用方法连接类和输入参数,做到类增加属性后,根据入参是否包含改属性自动赋值
如下是一种简单实现,具体如下:
1、Utils方法和测试的main函数
package com.hs.bigdata.ignite.testcase.utils; import com.hs.bigdata.ignite.testcase.env.EnvConfig; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; public class ConfigUtils { public static void main(String[] args) throws IOException, InvocationTargetException, IllegalAccessException { String filePath = "/config.properties"; Properties properties = getProperties(filePath); for (Object key : properties.keySet()) { System.out.println(key + "=" + properties.get(key)); } Map<String, String> configMap = propertiesToMap(properties); EnvConfig envConfig = (EnvConfig) mapToObject(new EnvConfig(), configMap); System.out.println(envConfig.toString()); } /** * configMap 属性赋值给对象,对象入参全部是String * @param object * @return */ public static Object mapToObject(Object object,Map<String,String> configMap) throws InvocationTargetException, IllegalAccessException { Method[] methods = object.getClass().getMethods(); for (Method method : methods) { String name = method.getName(); if(name.startsWith("set")) { String temp = name.substring(3); String key = temp.substring(0,1).toLowerCase() + temp.substring(1); String value = configMap.get(key); method.invoke(object, value); } } return object; } /** * properties 转成 Map * @param properties * @return */ public static Map<String,String> propertiesToMap(Properties properties){ int size = properties.size(); Map<String,String> map = new HashMap<>(size); Set<Map.Entry<Object, Object>> entries = properties.entrySet(); for (Object object : properties.keySet()) { String key = (String) object; String value = properties.getProperty(key, ""); map.put(key,value); } return map; } /** * 从指定目录下加载 properties文件到properties中 * @param path * @return */ public static Properties getProperties(String path) throws IOException { InputStream inputStream = null; InputStreamReader inputStreamReader = null; Properties properties = null; try { inputStream = ConfigUtils.class.getResourceAsStream(path); inputStreamReader = new InputStreamReader(inputStream, "UTF-8"); properties = new Properties(); properties.load(inputStreamReader); }finally { if(null != inputStreamReader){ inputStreamReader.close(); } if(null != inputStream){ inputStream.close(); } } return properties; } }
2、EnvConfig类
package com.hs.bigdata.ignite.testcase.env; public class EnvConfig { private String jdbcUrl; public String getJdbcUrl() { return jdbcUrl; } public void setJdbcUrl(String jdbcUrl) { this.jdbcUrl = jdbcUrl; } @Override public String toString() { return "EnvConfig{" + "jdbcUrl='" + jdbcUrl + '\'' + '}'; } }
本文来自博客园,作者:life_start,转载请注明原文链接:https://www.cnblogs.com/yangh2016/p/17109256.html