2017-04-11 35 views
0

我是Java新手。試圖在靜態變量下。我相信靜態變量處於類級別,並且在類加載期間僅會初始化一次。但是當我通過eclipse運行下面的程序時,每次靜態變量都得到重新初始化。我錯過了什麼嗎?獲得重新初始化的靜態變量

public class TestClass 
{ 
    private static Map<String,String> map= new HashMap<>(); 

    public void testStatic() 
    { 
     if(map.get("testkey")==null) 
     { 
      System.out.println("No values in the Map"); 
      map.put("testkey","testvalue"); 
     } 
     else 
     { 
      System.out.println("Map has value:"+ map.get("testkey")); 
     } 
    } 
} 

我從另一個測試類調用testStatic方法。

public class CallTestClass 
{ 
    public static void main(String... args) 
    { 
     TestClass tc= new TestClass(); 
     tc.testStatic(); 
    } 
} 

我假設,當我打電話給tc.testStatic();第一次,TestClass中的靜態地圖將沒有值,所以它應該打印出「地圖中沒有值」。但是如果我運行下一次它應該去其他部分和打印地圖有價值:測試值,因爲我在前面的執行價值。不過,每次我調用tc.testStatic()時,映射似乎都會重新初始化。方法。

+2

但是你的代碼只調用'testStatic'一次?第二次什麼時候? –

+2

當你說「再次運行它」時,你的意思是再次運行整個程序?程序結束時,即使靜態變量也會丟失。 –

+0

@MattiVirkkunen我正在運行CallTestClass兩次,而不是在單次運行中進行兩次調用。它是否使TestClass加載兩次? – GAK

回答

0

您應該第二次調用靜態方法。

public class CallTestClass{ 
    public static void main(String... args) 
    { 
    TestClass tc= new TestClass(); 
    tc.testStatic(); // "No values in the Map" 
    tc.testStatic(); // Map has value:testvalue 
    } 
    } 
1

靜態變量初始化一次,在執行的開始和當程序結束像其他變量都將丟失。

如果您想測試您的代碼,請在main中再次調用testStatic()方法以查看更新後的值。

public static void main(String... args) 
{ 
    TestClass tc= new TestClass(); 
    tc.testStatic(); 
    tc.testStatic(); 
} 
1

可變靜態變量是邪惡的!它使單元測試非常困難,應該避免在所有成本!

如果你需要在兩個地方的地圖,你應該使用依賴注入。

public static void main(String... args) { 
    Map<String, String> map = new HashMap<>(): 
    map.put("testkey", "testvalue"); 
    TestClass1 tc1 = new TestClass1(map); 
    TestClass2 tc2 = new TestClass2(map); 
    tc1.doStuff(); 
    tc2.doStuff(); 
} 

還要注意HashMap不是線程安全的所以可能不會進行並行處理

0

你可以簡單地創建使用new運營商TestClass 2級的對象,然後他們兩個調用testStatic(),看到工作結果。如註釋部分所述,不要再次嘗試執行應用程序,因爲它將重新放置類,因此靜態變量將丟失之前執行中設置的值。

public class CallTestClass { 
    public static void main(String... args){ 
     TestClass object1= new TestClass(); 
     object1.testStatic(); //this will execute the code inside the if condition, hence map will have an entry for the key "testkey" 

     TestClass object2= new TestClass(); 
     object2.testStatic(); //this will execute the else part. 
     //Even though object is new but as map is defined as 
     // static hence the state set is retained. 
    } 
} 

編輯正如另一種答案下文提到的,它的一個非常有效的提示,這樣的易變的static變量是邪惡的,必須加以避免,而不是這些在https://stackoverflow.com/a/43343979/504133

提到你可以注入在運行時的地圖