简体   繁体   中英

Parsing “true” / “false” in Java

What's the utility method that parses a boolean String properly? By properly I mean

"true" => true
"false" => false
"foo" => error

The parse methods in java.lang.Boolean are dodgy - they don't distinguish "false" from "foo". Anything else in Java libraries (or Guava, or Commons Lang) that does it properly?

Yes it's just be a couple lines, I just rather not write any line that I shouldn't have to. :-)

Honestly, this question is ridiculous. Yes, there are ways to do it built in (the Boolean utils API Apache Fan mentioned). But you're going out of your way to do something in a fancy way at the cost of A) productivity (stop wasting your time, write the three lines of code), and B) readability. What's easier to read:

if( "true".equals(myString) )

or

if( BooleanUtils.toBoolean(myString, "true", "false") )

I'd go for the first one every time. Even better, use the IgnoreCase option for the string comparison. The toBoolean is case sensitive, so "True" would actually throw an exception. Awesome! That's really useful!

if ( "true".equalsIgnoreCase(yourString) )
      return true;
else if ( "false".equalsIgnoreCase(yourString) )
      return false;
else
      throw new Exception();

There's not one.

Check out Boolean Utils form apache commons:

Boolean Utils API

Converts a String to a Boolean throwing an exception if no match found.

null is returned if there is no match.

BooleanUtils.toBoolean("true", "true", "false") = true
BooleanUtils.toBoolean("false", "true", "false") = false

How about the very simple:

EDIT: or am I missing the point...

boolean isTrue (String s) {
  return theString.toLowerCase().equals("true");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM