[英]Can I use a Java property value to reference a Java variable or constant?
假設我有一個名為DARK_CYAN的Java常數,它等於RBG十六進制值。 我想允許用戶利用JSON或XML文件來配置我的程序。 配置文件將具有鍵/值對,例如“ WINDOW_BACKGROUD:DARK_CYAN”。 當程序讀取配置屬性時,將看到窗口背景需要設置為DARK_CYAN。 是否可以使用字符串值“ DARK_CYAN”來引用Java常量DARK_CYAN?
當然,您可以為此使用Properties類。 mkyong網站上的一個很好的例子:
package com.mkyong.properties;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
public class App {
public static void main(String[] args) {
Properties prop = new Properties();
OutputStream output = null;
try {
output = new FileOutputStream("config.properties");
// set the properties value
prop.setProperty("database", "localhost");
prop.setProperty("dbuser", "mkyong");
prop.setProperty("dbpassword", "password");
// save properties to project root folder
prop.store(output, null);
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
您要跟蹤多少個常數? 您將需要解析JSON,並在常量的字符串值和常量本身之間創建一個Map。 因此,例如(假設RBG十六進制值為字符串):
Map<String, String> constantMap = new HashMap<String, String>();
Map.put("DARK_CYAN", DARK_CYAN);
然后,您可以解析JSON並執行constantMap.get(parsedStrname)
以獲取引用的常量值。
不明白為什么要使用xml來存儲屬性。 以“ propertyKey = propertyValue”形式定義屬性的常用方法。
要從屬性文件加載:
public Properties loadPropertiesResource(String fileLocation) {
Properties properties = new Properties();
InputStream inStream = Utils.class.getClassLoader().getResourceAsStream(fileLocation );
if (inStream == null)
throw new IOException("Properties Files is Missing - " + fileLocation );
properties.load(inStream);
return properties;
}
然后,您只是:
loadPropertiesResource(“ app.properties”)。getProperty(“ DARK_CYAN”);
從技術上講,您可以借助反射來實現。
使用所需的解析庫解析配置文件(JSON或XML)后,您將擁有一個包含文件屬性的對象。 如您提到的,這樣的屬性之一就是WINDOW_BACKGROUD
,其值為DARK_CYAN
。 現在,如果您不想對查詢進行硬編碼,則可以使用以下反射:
//winBackground value is read from the property file
String winBackground = (String) jsonObject.get("WINDOW_BACKGROUD");
Field f = YourConstantsClass.class.getField(winBackground);
//assuming that the value is of 'static int' type
int val = f.getInt(null);
如果常量值為任何其他類型,例如'double',則使用適當的get方法或使用if-else條件檢查類型。 我希望在您的類中將常量聲明為static final
。
編輯:順便說一句,您選擇用於在param文件中維護值名稱,然后將值名稱映射到常量類中的實際值的方法不是一個好的設計,因為當您想支持新的時需要更改您的類價值觀。 另外,您將需要假定將在props文件中定義在prop文件中使用的值名稱(例如DARK_CYAN
)。 如果不是,您將有一個反射異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.