0

私のプロパティオブジェクトがnullである理由を誰か教えてもらえますか? メソッドに渡す必要がありますか、それとももっと良い方法がありますか? パッケージ間でプロパティ オブジェクトを渡す必要がある場合はどうすればよいですか? ありがとう!

public class Test {
    private Properties properties = null;

    public static void main (String[] args) {
        testObject = new Test();
        Properties properties = new Properties(); // Then load properties from fileInputStream sucessfully

        utilityMethod(); 
    }

    private void utilityMethod() {
        properties.getProperty("test"); // Why do I get a null pointer exception?
    }
}
4

4 に答える 4

3

main() では、「プロパティ」への割り当ては、インスタンス フィールドではなく、ローカル変数に対するものです。

フィールドを設定したい場合は、次のようにできます。

private Properties properties = new Properties();

または、次のようなコンストラクターで:

 public Test() {
    properties = new Properties();
 }

または、クラス Test のすべてのインスタンスに対して単一の値が必要な場合は、次のようにします。

 private static Properties properties = new Properties();
于 2013-05-29T03:47:55.867 に答える
1

ここでProperties properties = new Properties();は別のものを使用しているので、今回はグローバルを使用します properties

public class Test {
    private Properties properties = null;

    public static void main (String[] args) {
        testObject = new Test();
        properties = new Properties(); // Now you are using global `properties` variable

        utilityMethod(); 
    }

    private void utilityMethod() {
        testObject .properties.getProperty("test"); // access by using testObject  object
    }
} 

または、静的として宣言することもできます

 private static Properties properties = new Properties();
于 2013-05-29T03:47:32.817 に答える
1

メイン内で再度宣言したため...

public static void main (String[] args) {
    testObject = new Test();
    // This is local variable whose only context is within the main method
    Properties properties = new Properties(); // Then load properties from fileInputStream sucessfully

    utilityMethod(); 
}

ps-あなたの例はコンパイルされutilityMethodstatic、メソッドのコンテキストから呼び出すことはできませんmain;)

于 2013-05-29T03:47:42.060 に答える
0

単純なタイプミスです。

「Properties properties = new Properties();」というプロパティのローカル インスタンスを作成しています。

@PSRの回答に従って、ここでグローバル変数を初期化します:)

于 2013-05-29T03:49:42.050 に答える