class strTest
{
public static boolean str(String string)
{
string=string.toLowerCase();
if (string.equals("yes") || string.equals("y") || string.equals("t"))
{
string = "true";
}
return Boolean.getBoolean(string);
}
public static void main(String[] args)
{
System.out.println(str("true") + " " + str("Yes"));
}
}
为什么打印出来是两个false呢?Boolean.getBoolean(String name)这个方法在帮助文档是这样说的:当且仅当以参数命名的系统属性存在,且等于 "true" 字符串时,才返回 true。可我在系统里建立了一个名为true,值为true的系统属性,打印出来还是false.这个方法到底是做什么用的?请懂的朋友,给予解答,谢谢!
http://hi.baidu.com/love_%D7%CF/blog/item/0f0c991390dc1a58f919b82a.html
老实说,我个人不建议把改方法作为Boolean的static方法其实和它没有太强烈的关系。System.hasProperty();这样的方法不是更能让使用者清楚?
public static void main(String[] args)
{
System.setProperty("true","true");
System.out.println(str("true") + " " + str("Yes"));//这样就会输出true true
}
当且仅当以参数命名的系统属性存在,且等于 "true" 字符串时,才返回 true。
System.setProperty("true","true");
没有设置系统属性
个人认为,这个方法作用很小并且容易引起错误,开发中要杜绝使用该方法。
像楼主的代码,既然已经用String.equals方法进行判断了,不如直接返回true。
if (string.equals("yes") || string.equals("y") || string.equals("t"))
{
return true;
}这样即容易理解效率还高。
from apis
你后面的才成立
API已经说得很清楚了,有名为true的property且值为“true”,返回true,没有则返回false啦public static void main(String[] args) {
// TODO Auto-generated method stub if (System.getProperty("true") != null)
{
System.out.println("has property[true]");
System.out.println(Boolean.getBoolean("true"));
}else{
System.out.println("no property[true]");
System.out.println(Boolean.getBoolean("true"));
}
System.setProperty("true", "true"); if (System.getProperty("true") != null)
{
System.out.println("has property[true]");
System.out.println(Boolean.getBoolean("true"));
}else{
System.out.println("no property[true]");
System.out.println(Boolean.getBoolean("true"));
}
System.setProperty("true", "false"); if (System.getProperty("true") != null)
{
System.out.println("has property[true]");
System.out.println(Boolean.getBoolean("true"));
}else{
System.out.println("no property[true]");
System.out.println(Boolean.getBoolean("true"));
}
}