2013-05-29 18 views
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? 
    } 
} 
+0

你應該閱讀 - http://docs.oracle.com/javase/tutorial/java/javaOO/variables.html –

+0

,因爲你沒有將Test.properties設置爲其他任何內容。 –

回答

3

在main()中,您對「properties」的賦值是針對局部變量,而不是實例字段。

如果你想設置的現場,你可以這樣做是這樣的:

private Properties properties = new Properties(); 

或者在這樣的構造:

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

或者,如果你想有一個單一的價值對於類Test的所有實例,如下所示:

private static Properties properties = new Properties(); 
1

這裏Properties properties = new Properties();你正在使用其他one.So使用全局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(); 
+0

你能解釋一下你做了什麼(我可以看到),但是看到OP沒有做到,它可能會更有幫助,然後把答案扔給他們;) – MadProgrammer

+0

@MadProgrammer謝謝你的建議。你說的對。 – PSR

+1

這不是靜態的。我認爲它應該是'testObject.properties'。 –

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-你的榜樣將無法編譯,因爲utilityMethod不是static並且不能從main方法的上下文中調用;)

+0

main()不是構造函數。 –

+0

@ AndyThomas-Cramer從技術角度來看 - 它確實「構建」了某些東西;) – MadProgrammer

0

這是一個簡單的錯字。

您正在創建屬性的本地實例「Properties properties = new Properties();」

如回答@PSR,這裏初始化的全局變量:)

相關問題