您的位置:首页 > 编程语言 > Java开发

java常量使用比较好的方法

2016-01-13 15:45 423 查看
1.首先建立一个工具类

public class AppConst {

private static Map<String,String> map=new HashMap<String,String>();
static {

try {
InputStream inputStream=AppConst.class.getClassLoader().getResourceAsStream("app-const.properties");
Properties properties= new Properties();
properties.load(inputStream);
Iterator<Map.Entry<Object,Object>> iterator=properties.entrySet().iterator();

Map<String,String> tmap=new HashMap<String,String>();
while (iterator.hasNext())
{
Map.Entry<Object,Object> objectObjectEntry= iterator.next();
tmap.put(objectObjectEntry.getKey().toString(),objectObjectEntry.getValue().toString());
}
map.clear();
map.putAll(tmap);
} catch (IOException e) {
e.printStackTrace();
}
}
public static String getValue(String key)
{
return map.get(key);
}
}


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

url=http://www.baidu.com


  

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

public interface URLConst {
public interface URL {
public final static String URL = "url";
}

}


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

AppConst.getValue(URLConst.URL.URL);


总结:这种方法便于常量的管理
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: