4

私は次のコードを持っています:

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引数」から読み取り、変数に割り当てます。

static final 変数はクラスのロード時にのみ初期化されるため、パラメーターを渡すのを忘れた場合に例外をキャッチするにはどうすればよいですか。

現在、「property_file_location」変数を使用している場合、次の場合に例外が発生します。

  • 値が存在し、場所が間違っている場合、FileNotFound 例外が発生します。
  • 正しく初期化されていない場合 (値が null の場合)、NullPointerException がスローされます。

初期化時にのみ 2 番目のケースを処理する必要があります。

2 番目の変数の場合も同様です。

全体のアイデアは

  • アプリケーション構成パラメーターを初期化します。
  • 正常に初期化された場合は、続行します。
  • そうでない場合は、ユーザーに警告し、アプリケーションを終了します。
4

3 に答える 3

4

次の方法でキャッチできます。

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;
    }
}
于 2013-07-26T06:14:54.153 に答える
2

残りの回答で示唆されているように、静的初期化ブロックを使用できます。この機能を静的ユーティリティ クラスに移動して、引き続きワンライナーとして使用できるようにすることをお勧めします。その後、デフォルト値を提供することもできます。

// 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
}
于 2013-07-26T06:30:43.563 に答える
0

静的ブロックを使用したい場合があります:

public static final property_file_location;
static {
  try {
    property_file_location = System.getProperty("app.vmargs.propertyfile");
  } catch (xxx){//...}
}
于 2013-07-26T06:16:05.807 に答える