Looks up a property, first in the environment, then the system properties. - Java java.lang

Java examples for java.lang:System

Description

Looks up a property, first in the environment, then the system properties.

Demo Code


//package com.java2s;

import java.util.Properties;

public class Main {
    /**//from w w  w  .ja  v a 2  s.co m
     * Looks up a property, first in the environment, then the system properties. 
     * If not found in either, returns the supplied default.
     * @param name The name of the key to look up.
     * @param defaultValue The default to return if the name is not found.
     * @param properties An array of properties to search in. If empty or null, will search system properties. The first located match will be returned.
     * @return The located value or the default if it was not found.
     */
    public static String getEnvThenSystemProperty(String name,
            String defaultValue, Properties... properties) {

        String value = System.getenv(name.replace('.', '_'));
        if (value == null) {
            value = mergeProperties(properties).getProperty(name);
        }
        if (value == null) {
            value = defaultValue;
        }
        return value;
    }

    /**
     * Merges the passed properties
     * @param properties The properties to merge
     * @return the merged properties
     */
    public static Properties mergeProperties(Properties... properties) {
        Properties allProps = new Properties(System.getProperties());
        for (int i = properties.length - 1; i >= 0; i--) {
            if (properties[i] != null && properties[i].size() > 0) {
                allProps.putAll(properties[i]);
            }
        }
        return allProps;
    }
}

Related Tutorials