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