[英]Catch exception while initializing static final variable
我有以下代码:
public class LoadProperty
{
public static final String property_file_location = System.getProperty("app.vmargs.propertyfile");
public static final String application-startup_mode = System.getProperty("app.vmargs.startupmode");
}
它从“ VM参数”中读取并分配给变量。
由于静态最终变量仅在类加载时初始化,因此如果有人忘记传递参数,如何捕获异常。
截至目前,当我使用'property_file_location'变量时,在以下情况下会遇到异常:
我只需要在初始化时处理第二种情况。
类似的是第二变量的情况。
整个想法是
您可以通过以下方式捕获它:
public class LoadProperty
{
public static final String property_file_location;
static {
String myTempValue = MY_DEFAULT_VALUE;
try {
myTempValue = System.getProperty("app.vmargs.propertyfile");
} catch(Exception e) {
myTempValue = MY_DEFAULT_VALUE;
}
property_file_location = myTempValue;
}
}
您可以按照其余答案的建议使用静态初始化程序块。 甚至最好将此功能移至静态实用程序类,以便您仍然可以将它们用作单行代码。 您甚至可以提供默认值,例如
// PropertyUtils is a new class that you implement
// DEFAULT_FILE_LOCATION could e.g. out.log in current folder
public static final String property_file_location = PropertyUtils.getProperty("app.vmargs.propertyfile", DEFAULT_FILE_LOCATION);
但是,如果不希望这些属性始终存在,则建议不要将它们初始化为静态变量,而应在正常执行期间读取它们。
// in the place where you will first need the file location
String fileLocation = PropertyUtils.getProperty("app.vmargs.propertyfile");
if (fileLocation == null) {
// handle the error here
}
您可能要使用静态块:
public static final property_file_location;
static {
try {
property_file_location = System.getProperty("app.vmargs.propertyfile");
} catch (xxx){//...}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.