java常量使用比较好的方法

1.首先建立一个工具类

 1 public class AppConst {
 2     
 3     private static Map<String,String> map=new HashMap<String,String>();
 4     static {
 5 
 6         try {
 7             InputStream inputStream=AppConst.class.getClassLoader().getResourceAsStream("app-const.properties");
 8             Properties properties= new Properties();
 9             properties.load(inputStream);
10             Iterator<Map.Entry<Object,Object>> iterator=properties.entrySet().iterator();
11 
12             Map<String,String> tmap=new HashMap<String,String>();
13             while (iterator.hasNext())
14             {
15                 Map.Entry<Object,Object> objectObjectEntry= iterator.next();
16                 tmap.put(objectObjectEntry.getKey().toString(),objectObjectEntry.getValue().toString());
17             }
18             map.clear();
19             map.putAll(tmap);
20         } catch (IOException e) {
21             e.printStackTrace();
22         }
23     }
24     public static String getValue(String key)
25     {
26         return map.get(key);
27     }
28 }

 

2.然后在配置文件中 app-const.properties 中配置你需要的常量

url=http://www.baidu.com

  

3.其次在你的常量类中命名变量名称

1 public interface URLConst {
2     public interface URL {
3         public final static String URL = "url";
4     }
5     
6 }

 

4.最后使用此种方法访问即可

AppConst.getValue(URLConst.URL.URL);

 

 

总结:这种方法便于常量的管理

 

posted @ 2016-01-13 15:45  全力以赴001  阅读(1846)  评论(0编辑  收藏  举报