转载:http://www.abc188.com/info/html/chengxusheji/Javajishu/20080226/50390_2.html
一般有以下四种把字符串转换成boolean的方法,各自有各自的实现思路和特点:
1.最基本的,先看JDK的做法:
Java,lang.Boolean的toBoolean(String name)是个私有方法。
private static boolean toBoolean(String name) {
return ((name != null) && name.equalsIgnoreCase("true"));
}
可以看到,除了不区分大小写的字符串true外,其余的字符串均表示false;
2.JSP中的标签.
通过试验,发现在jsp标签中,on也会被转换成true的。
完整的javaBean:
-------------------------------------
package com.lizongbo;
/**
*
Title: lizongbo demo
*
Description: lizongbo的测试程序
*
Copyright: Copyright (c) 2005
*
Company: lizongbo
* @author lizongbo lizongbo
* @version 1.0
*/
public class TestbooleanBean {
private boolean sample = false;
//Access sample property
public boolean getSample() {
return sample;
}
//Access sample property
public void setSample(boolean newValue) {
sample = newValue;
}
}
-------------------------------------
jsp文件
-------------------------------------
testboolean
Enter new value :
Value of Bean property is :
-------------------------------------
通过察看tomcat源代码可以找到其实现boolean转换的代码
org.apache.jASPer.runtime.
JspRuntimeLibrary.java
public static Object convert(String propertyName, String s, Class t,
Class propertyEditorClass)
throws JasperException
{
try {
if (s == null) {
if (t.equals(Boolean.class) || t.equals(Boolean.TYPE))
s = "false";
else
return null;
}
if (propertyEditorClass != null) {
return getValueFromBeanInfoPropertyEditor(
t, propertyName, s, propertyEditorClass);
} else if ( t.equals(Boolean.class) || t.equals(Boolean.TYPE) ) {
if (s.equalsIgnoreCase("on") || s.equalsIgnoreCase("true"))
s = "true";
else
s = "false";
return new Boolean(s);
}
由此可以看出,jsp标签中是支持把不区分大小写的“on”和“true”都转换成true的。
3.org.apache.commons.lang.BooleanUtils.toBoolean(String str);
BooleanUtils提供了多种转换,这里只看它对字符串的转换。
看它的代码可以知道支持把不分大小写的“yes”,“on”,“true”都转换成true;
public static boolean toBoolean(String str) {
if ("true".equalsIgnoreCase(str)) {
return true;
} else if ("on".equalsIgnoreCase(str)) {
return true;
} else if ("yes".equalsIgnoreCase(str)) {
return true;
}
// no match
return false;
}
ps: apache commons configuration 中的Configuration getBoolean(String key)就是调用的这个转换方法。
4.com.opensymphony.util.TextUtils.parseBoolean(String in);
这个方法支持转换成true的范围最多最广也最灵活,容错性高,尽可能的满足了现实生活习惯,但是,不支持把“on”转换成true
/**
* Convert a String to an boolean.
* Accepts: 1/0, yes/no, true/false - case insensitive. If the value does
* not map to "true,", false
is returned.
*
* @param in String to be parsed.
* @return boolean representation of String.
*/
public final static boolean parseBoolean(String in) {
in = noNull(in);
if (in.length() == 0) {
return false;
}
switch (in.charAt(0)) {
case '1':
case 'y':
case 'Y':
case 't':
case 'T':
return true;
}
return false; }