getBoolean(String str) and valueOf(String str) of Boolean class gives different output

后端 未结 5 1934
野性不改
野性不改 2020-12-29 18:38

I am surprised to know that getBoolean() and valueOf() method returns different results for the same input string.

I have tried to pass the

相关标签:
5条回答
  • 2020-12-29 19:06
    class Boo1
    {    
        public static void main(String[] args)
        {    
           System.setProperty("true","true");
           System.setProperty("false","true");
    
           boolean d=Boolean.getBoolean("true");
    
           System.out.println(d);   
       }
    }
    
    0 讨论(0)
  • 2020-12-29 19:12

    I too found this issue recently when using Boolean.getBoolean() . In addition if you want to have a null check you can use Boolean.parseBoolean which will return false in case of nulls

    0 讨论(0)
  • 2020-12-29 19:16

                                         The API-documentation is your friend.

    • Boolean.getBoolean probably doesn't do what you think it does:

      Returns true if and only if the system property named by the argument exists and is equal to the string "true".


    • Boolean.valueOf is probably what you're looking for:

      The Boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true".

    0 讨论(0)
  • 2020-12-29 19:16

    Boolean.getBoolean must be the worst placed method in java. One of the big WTF.

    Why wasn't it placed in System or Properties or whatever?

    So to answer your question - yes, it is a very confusing thing and you can just click on the method in your IDE to see the code or read the javadoc.

    Here's the source code:

     public static boolean getBoolean(String name) {
            boolean result = false;
            try {
                result = toBoolean(System.getProperty(name));
            } catch (IllegalArgumentException e) {
            } catch (NullPointerException e) {
            }
            return result;
        }
    
    0 讨论(0)
  • 2020-12-29 19:24

    The javadoc of getBoolean clearly state that it searches the System Properties. The value that you pass to it is the name of the system property, not a "true" or "false" string.

    E.g., `var b = Boolean.getBoolean("some.property");

    0 讨论(0)
提交回复
热议问题