简体   繁体   English

解析 Java 中的“真”/“假”

[英]Parsing “true” / “false” in Java

What's the utility method that parses a boolean String properly?正确解析 boolean 字符串的实用方法是什么? 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". java.lang.Boolean 中的解析方法很狡猾——它们不区分“假”和“富”。 Anything else in Java libraries (or Guava, or Commons Lang) that does it properly? Java 库(或 Guava 或 Commons Lang)中的其他任何东西都可以正常工作吗?

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).是的,有一些方法可以内置(提到 Boolean utils API Apache Fan)。 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.但是你会以一种奇特的方式做某事,代价是 A) 生产力(停止浪费你的时间,编写三行代码)和 B) 可读性。 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.我每次都是第一个 go 。 Even better, use the IgnoreCase option for the string comparison.更好的是,使用 IgnoreCase 选项进行字符串比较。 The toBoolean is case sensitive, so "True" would actually throw an exception. toBoolean 区分大小写,因此“True”实际上会引发异常。 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 form apache commons:

Boolean Utils API Boolean 实用程序 API

Converts a String to a Boolean throwing an exception if no match found.如果未找到匹配项,则将字符串转换为 Boolean 引发异常。

null is returned if there is no match.如果没有匹配,则返回 null。

BooleanUtils.toBoolean("true", "true", "false") = true BooleanUtils.toBoolean("true", "true", "false") = true
BooleanUtils.toBoolean("false", "true", "false") = false 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");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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