java中属于常量_java中的常量和属性
Java最佳實踐建議將屬性作為常量讀取.那么,您認為達到目標的最佳方法是什么?我的方法是:一個Configuration類只讀取一次屬性文件(單例模式),并使用此類在需要時讀取屬性作為常量.并存儲一個Constants類:
>屬性名稱可在屬性文件中找到它們(例如app.database.url).
>靜態常量(我不希望用戶配置的靜態常量,例如
CONSTANT_URL = “myurl.com”).
public final class Configurations {
private Properties properties = null;
private static Configurations instance = null;
/** Private constructor */
private Configurations (){
this.properties = new Properties();
try{
properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(Constants.PATH_CONFFILE));
}catch(Exception ex){
ex.printStackTrace();
}
}
/** Creates the instance is synchronized to avoid multithreads problems */
private synchronized static void createInstance () {
if (instance == null) {
instance = new Configurations ();
}
}
/** Get the properties instance. Uses singleton pattern */
public static Configurations getInstance(){
// Uses singleton pattern to guarantee the creation of only one instance
if(instance == null) {
createInstance();
}
return instance;
}
/** Get a property of the property file */
public String getProperty(String key){
String result = null;
if(key !=null && !key.trim().isEmpty()){
result = this.properties.getProperty(key);
}
return result;
}
/** Override the clone method to ensure the "unique instance" requeriment of this class */
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}}
Constant類包含對屬性和常量的引用.
public class Constants {
// Properties (user configurable)
public static final String DB_URL = "db.url";
public static final String DB_DRIVER = "db.driver";
// Constants (not user configurable)
public static final String PATH_CONFFILE = "config/config.properties";
public static final int MYCONSTANT_ONE = 1;
}
屬性文件將是:
db.url=www.myurl.com
db.driver=mysql
要讀取屬性和常量將是:
// Constants
int i = Constants.MYCONSTANT_ONE;
// Properties
String url = Configurations.getInstance().getProperty(Constants.DB_URL);
你認為這是一個好方法嗎?在Java中讀取屬性和常量的方法是什么?
提前致謝.
總結
以上是生活随笔為你收集整理的java中属于常量_java中的常量和属性的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java实现min函数_AcWing 4
- 下一篇: 一个深圳程序员被一美女骗到东莞迷強