understand "on"/"off", "yes"/"no", "1"/"0" as boolean values (analogous to CustomBooleanEditor)

This commit is contained in:
Juergen Hoeller
2009-10-01 11:18:48 +00:00
parent b465f204bd
commit 7a700edaa7
2 changed files with 38 additions and 7 deletions

View File

@@ -16,27 +16,53 @@
package org.springframework.core.convert.support;
import java.util.HashSet;
import java.util.Set;
import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;
/**
* Converts String to a Boolean.
*
* @author Keith Donald
* @author Juergen Hoeller
* @since 3.0
*/
final class StringToBooleanConverter implements Converter<String, Boolean> {
private static final Set<String> trueValues = new HashSet<String>(4);
private static final Set<String> falseValues = new HashSet<String>(4);
static {
trueValues.add("true");
falseValues.add("false");
trueValues.add("on");
falseValues.add("off");
trueValues.add("yes");
falseValues.add("no");
trueValues.add("1");
falseValues.add("0");
}
public Boolean convert(String source) {
if (source.equals("")) {
String value = (source != null ? source.trim() : null);
if (!StringUtils.hasLength(value)) {
return null;
} else if (source.equals("true")) {
}
else if (trueValues.contains(value)) {
return Boolean.TRUE;
}
else if (source.equals("false")) {
else if (falseValues.contains(value)) {
return Boolean.FALSE;
}
else {
throw new IllegalArgumentException("Invalid boolean string '" + source + "'; expected \"\", 'true', or 'false'");
throw new IllegalArgumentException("Invalid boolean value '" + source + "'");
}
}