不让用常量类,那就用.properties文件配置,放在根目录。
1 import java.util.HashMap; 2 import java.util.Iterator; 3 import java.util.Map; 4 import java.util.Properties; 5 6 /** 7 * Created by syl on 2017/12/12 0007. 读取常量properties文件 8 */ 9 public class PropertyUtil { 10 @SuppressWarnings("rawtypes")11 private static Map map = null; 12 13 @SuppressWarnings({ "rawtypes", "unchecked" })14 private static void loadFile() { 15 map = new HashMap(); 16 try { 17 Properties p = new Properties(); 18 p.load(PropertyUtil.class.getClassLoader().getResourceAsStream("params.properties")); 19 Iterator it = p.keySet().iterator(); 20 while (it.hasNext()) { 21 String key = (String) it.next(); 22 String value = p.getProperty(key); 23 map.put(key, value); 24 } 25 } catch (Exception e) { 26 e.printStackTrace(); 27 } 28 } 29 30 public static String getValue(String str) { 31 if (map == null) { 32 loadFile(); 33 } 34 return (String) map.get(str); 35 } 36 37 public static void main(String[] args) {38 String s = PropertyUtil.getValue("test");39 System.out.println(s);40 }41 }
控制台输出: