package com.qiwu.chatbotbackend.Config; import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStream; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Properties; import java.util.Set; public class ConfigInitializer { private static final String CONFIGFILE = "config.properties"; private static final String CLASSPREFIX = "com.qiwu.chatbotbackend.config.config"; /** * 读取配置文件 */ public static void init() { InputStream configInputStream; try { BufferedReader bufferedReader = new BufferedReader(new FileReader(CONFIGFILE)); Properties properties = new Properties(); properties.load(bufferedReader); initNextLevel(properties, Config.class); } catch (Exception e) { e.printStackTrace(); } finally { } } public static void initNextLevel(Properties properties, Class nowClass) throws IllegalAccessException { String baseClassName = nowClass.getName().toLowerCase().replaceAll("\\$", "\\."); String shortName = baseClassName.replaceAll(CLASSPREFIX, "").replaceFirst("\\.", ""); //key集合 Set keys = properties.keySet(); for (Field field : nowClass.getFields()) { if (Modifier.isPublic(field.getModifiers()) && Modifier.isStatic(field.getModifiers())) { String classParam = field.getName().toLowerCase(); if (shortName.equals("")) { if (keys.contains(classParam)) { pushNewValue(classParam, properties, field); } } else { if (keys.contains(shortName + "." + classParam)) { pushNewValue(shortName + "." + classParam, properties, field); } } } } for (Class aClass : nowClass.getClasses()) { initNextLevel(properties, aClass); } } public static void pushNewValue(String classParam, Properties properties, Field field) throws IllegalAccessException { String value = properties.getProperty(classParam); if (value != null) { Class type = field.getType(); if (type.equals(int.class)) field.set(null, Integer.valueOf(value)); else if (type.equals(String.class)) field.set(null, value); else if (type.equals(long.class)) field.set(null, Long.valueOf(value)); else if (type.equals(boolean.class)) field.set(null, Boolean.valueOf(value)); else if (type.isEnum()) field.set(null, Enum.valueOf((Class) type, value.toUpperCase())); } } }