繁体   English   中英

我可以使用Java属性值来引用Java变量或常量吗?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM