相关文章:https://blog.csdn.net/5iasp/article/details/46652115
https://blog.csdn.net/z69183787/article/details/39343259 Java Field 详解
https://www.cnblogs.com/gmq-sh/p/5942065.html java获取对象属性类型、属性名称、属性值
https://www.cnblogs.com/hafiz/p/5876243.html
五种方式让你在java中读取properties文件内容再也不是难题html
思路:建立工具类 实现读取配置文件存入缓冲流,判断静态变量在缓冲流中是否存在, 并赋值的过程java
-具体实现:apache
注意事项:工具
Field field = AlipayConfig.class.getDeclaredField(key); field.set(AlipayConfig.class, value);
package com.youboy.order.utils; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Enumeration; import java.util.Properties; import org.apache.log4j.Logger; import com.youboy.alipay.constant.AlipayConfig; /** * @author wanpan * @version 建立时间:2018年4月10日 上午10:00:53 * 类说明 */ public class PropertiesUtil { private final static Logger logger = Logger.getLogger(PropertiesUtil.class); private static Properties props; /* static { loadProps("zfb_dev"); }*/ synchronized private static void loadProps(String propName) { logger.info("开始加载properties文件内容......."); props = new Properties(); InputStream in = null; try { /* * <!--第一种,经过类加载器进行获取properties文件流--> * in = PropertyUtil.class.getClassLoader().getResourceAsStream( * "jdbc.properties"); * <!--第二种,经过类进行获取properties文件流--> */ in = PropertiesUtil.class.getResourceAsStream("/"+propName+".properties"); props.load(in); } catch (FileNotFoundException e) { logger.error(propName+".properties文件未找到",e); } catch (IOException e) { logger.error("出现IOException",e); } finally { try { if (null != in) { in.close(); } } catch (IOException e) { logger.error(".properties文件流关闭出现异常",e); } } logger.info("加载properties文件内容完成..........."); logger.info("properties文件内容:" + props); } public static boolean loadPropertitesToClass(String properties,Class c) { boolean b = false; loadProps(properties); ArrayList<String> filedNames = getFiledName(c); Enumeration<?> enumeration = props.keys(); while (enumeration.hasMoreElements()) { String key = enumeration.nextElement().toString(); String value = props.getProperty(key); if (filedNames.contains(key)) { try { Field field = AlipayConfig.class.getDeclaredField(key); field.set(AlipayConfig.class, value); b = true; } catch (Exception e) { logger.error(c.getName()+"静态变量赋值出错",e); } } } return b; } public static String getProperty(String key,String pros) { if (null == props) { loadProps(pros); } return props.getProperty(key); } public static String getProperties(String key) { if (null == props) { return null; } return props.getProperty(key); } private static ArrayList<String> getFiledName(Class c) { Field[] fields = c.getDeclaredFields(); ArrayList<String> fieldNames = new ArrayList<String>(); for (int i = 0; i < fields.length; i++) { fieldNames.add(fields[i].getName()); } return fieldNames; } }