如果配置中存在,则设置默认值.属性使用它,如果在命令行上被覆盖则使用它



未经测试的代码(只是想出来的),但我认为一定有一个更优雅的方法来做到这一点。

设置变量有三种方式:

  1. 直接赋值
  2. 从属性文件中读取(可能不存在)
  3. 从命令行读取它(可以是多个参数或没有)

数值越高优先。我该怎么做呢?

public static final String APP_DOWNLOAD_PATH;
[...]
// If download path is not defined in config.properties, set it to the app dir.
String download = properties.getProperty("download", System.getProperty("user.dir"));
// Override if download path is set via command line.
String override = null;
try {
override = System.getProperty("download");
} catch (NullPointerException | IllegalArgumentException ok) {
// property is either not found or empty.
}
String APP_DOWNLOAD_PATH = (override == null || override.isEmpty()) ? download : override;

E: add restrictions.

我认为直接的方法是最好的。例如:

public static final String APP_DOWNLOAD_PATH = "foo";
public static void main(String... args) {
String dwnPath = null;

if(args.length > 0) {
dwnPath = args[0];
} else if(System.getProperty("download") != null) { // don't need try-catch, "download" is not null and not empty ("")
// not DRY at all
dwnPath = System.getProperty("download");
} else {
dwnPath = APP_DOWNLOAD_PATH;
}
// rest of program
}

上面的内容也可以提取到它自己的函数中,从而形成一行代码:

String dwnPath = getDownloadPath(args, System.getProperty("download"), APP_DOWNLOAD_PATH);

提取的函数也可以比上面的代码更优雅:

/** Documentation */
public static String getDownloadPath(String[] args, String property, String default) {
return (args.length > 0) ? args[0] : (property != null) ? property : default;
}

如果可以使用外部库,那么这个apache commons方法可能是有用的-

StringUtils.firstNonEmpty(System.getProperty("download"), 
properties.getProperty("download", System.getProperty("user.dir")), 
"some value");

最新更新