简体   繁体   中英

Can I use a Java property value to reference a Java variable or constant?

Assume I have a Java constant called DARK_CYAN that is equal to an RBG hex value. I'd like to allow a user to utilize a JSON or XML file to configure my program. The configuration file would have key/value pairs such as "WINDOW_BACKGROUD:DARK_CYAN". When the program reads in the configuration properties, it would see that the window background needs to be set to DARK_CYAN. Is it possible to reference the Java constant DARK_CYAN using a string value of "DARK_CYAN"?

Sure, you can use Properties class for that. A good example from mkyong website:

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

    }
  }
}

How many constants are you keeping track of? You'll need to parse the JSON and explicity create a Map between the string value of the constant and the constant itself. So, for example (assuming that the RBG hex value is a string):

Map<String, String> constantMap = new HashMap<String, String>();
Map.put("DARK_CYAN", DARK_CYAN);

Then, you can parse the JSON and do a constantMap.get(parsedStrname) to get the constant value referenced.

Don't understand why would use xml to store the properties. The common approach to define properties in form "propertyKey=propertyValue".

To load from properties file:

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

Then you just:

loadPropertiesResource("app.properties").getProperty("DARK_CYAN");

Technically, you can achieve this with help of reflection.

Once you have parsed your config file (JSON or XML) using the required parsing library, you would have an object containing the properties from your file. One such property would be WINDOW_BACKGROUD as you mentioned, with the value DARK_CYAN . Now, if you don't want to hard-code the lookup, you can use reflection as below:

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

If the constant value is of any other type such as 'double', use appropriate get method or have if-else conditions to check the types. I hope, the constants are declared static final in your class.

EDIT: btw, the approach that you have chosen for maintaining value names in the param file and then map the value names to actual values in your constant class is not a good design, as you need to change your class when you want to support new values. Also, you would need to assume that the value name (eg DARK_CYAN ) that you use in the prop file would be defined in your constants class. If it is not, you would have a reflection exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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