关于Java的Boolean.getBoolean方法

关于Java的Boolean.getBoolean方法


Boolean.getBoolean(String name)这个方法经常误导使用者,使用者经常会以为是通过一个String的"true"转换为Boolean的true,但结果却不是这样的.


看一下API的解释:

英文的API:----------------------------------------------------------------------------------------------------
public static boolean getBoolean(String name)
Returns true if and only if the system property named by the argument exists and is equal to the string "true". (Beginning with version 1.0.2 of the JavaTM platform,

the test of this string is case insensitive.) A system property is accessible through getProperty, a method defined by the System class. 
If there is no property with the specified name, or if the specified name is empty or null, then false is returned.

Parameters: 
name - the system property name. 
Returns: 
the boolean value of the system property. 
See Also: 
System.getProperty(java.lang.String), System.getProperty(java.lang.String, java.lang.String)

中文的API:----------------------------------------------------------------------------------------------------
public static boolean getBoolean(String name)当且仅当以参数命名的系统属性存在,且等于 "true" 字符串时,才返回 true。(从 JavaTM 1.0.2 平台开始,字符串的测试不再区分大

小写。)通过 getProperty 方法可访问系统属性,此方法由 System 类定义。 
如果没有以指定名称命名的属性或者指定名称为空或 null,则返回 false。


参数:
name - 系统属性名。 
返回:
系统属性的 boolean 值。
另请参见:
System.getProperty(java.lang.String), System.getProperty(java.lang.String, java.lang.String)


这里需要注意的是“系统属性”,也就是说getBoolean是用于访问Java系统属性的方法,与将字符串"true"转成boolean的true没有任何关系。
换句话说这个getBoolean不是转换方法,而是获取Java系统属性的方法。

 

以下是Boolean.getBoolean的正确用法:


public class TestGetBoolean
{

public static void main(String[] args){

/*
*当且仅当以参数命名的系统属性存在,且等于 "true" 字符串时,才返回 true
*/

//大写的true返回为false,必须是小写的true
String s1 = "true";

String s2 = new String("true");

//这里将s1存放到Java系统属性中了.
System.setProperty(s1,"true");

System.setProperty(s2,"true");

//这里从系统属性中获取s1,所以获取到了。
System.out.println(Boolean.getBoolean(s1));//true

System.out.println(Boolean.getBoolean(s2));//true

String s3 = "true";

//很明显s3并没有存放到系统属性中所以返回false。
System.out.println(Boolean.getBoolean(s3));//false

//这个更是错的了,呵呵。
System.out.println(Boolean.getBoolean("true"));//false
}

}


以下是将字符串"true"转成boolean的true的正确用法:


正确用法:boolean repeatIndicator = Boolean.valueOf("true").booleanValue();
   或者也可以使用Boolean.parseBoolean()方法,但此方法是jdk1.5以后推出的。

总结:

Java在将字符串的值转换为相应的类型时,需要多使用parse开头的方法,或者是valueOf之类的方法。

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值