相信不少人被Boolean.getBoolean(String name)欺騙過,想固然的認爲它是將「true」或者「false」轉換爲Boolean類型的API。錯,徹底不是!下面咱們就詳細講一下Boolean.getBoolean(String name)的用法。code
首先咱們看下Boolean.getBoolean(String name)的源碼:get
public static boolean getBoolean(String name) { boolean result = false; try { result = parseBoolean(System.getProperty(name)); } catch (IllegalArgumentException | NullPointerException e) { } return result; }
從源代碼中能夠看出Boolean.getBoolean首先會根據name從系統屬性中獲取name屬性的值,而後對name屬性對應的值進行轉換。源碼
正確的用法用法應該是:io
public static void main(String[] args) { String value = "true"; String key= "key"; System.setProperty(key, value); Boolean flag = Boolean.getBoolean(key); if(flag) { System.out.println("key is true"); } else { System.out.println("key is not true"); } }
若是想將「true」或者「false」轉換爲Boolean類型值,可使用Boolean.parseBoolean(String s)。static