日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java中属于常量_java中的常量和属性

發(fā)布時間:2025/3/15 编程问答 13 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java中属于常量_java中的常量和属性 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

Java最佳實(shí)踐建議將屬性作為常量讀取.那么,您認(rèn)為達(dá)到目標(biāo)的最佳方法是什么?我的方法是:一個Configuration類只讀取一次屬性文件(單例模式),并使用此類在需要時讀取屬性作為常量.并存儲一個Constants類:

>屬性名稱可在屬性文件中找到它們(例如app.database.url).

>靜態(tài)常量(我不希望用戶配置的靜態(tài)常量,例如

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);

你認(rèn)為這是一個好方法嗎?在Java中讀取屬性和常量的方法是什么?

提前致謝.

總結(jié)

以上是生活随笔為你收集整理的java中属于常量_java中的常量和属性的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。