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 jus开发者_运维技巧t rather not write any line that I shouldn't have to. :-)
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
if ( "true".equalsIgnoreCase(yourString) )
return true;
else if ( "false".equalsIgnoreCase(yourString) )
return false;
else
throw new Exception();
There's not one.
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!
How about the very simple:
EDIT: or am I missing the point...
boolean isTrue (String s) {
return theString.toLowerCase().equals("true");
}
精彩评论