http://jira.springframework.org/browse/SWF-827 Add support for converting Java 5 Enums automatically

needed to bump source target to 1.5 in order to compile the enum
This commit is contained in:
Scott Andrews
2008-08-12 18:01:40 +00:00
parent f2f48d2cbc
commit 1928c335cd
6 changed files with 102 additions and 8 deletions

View File

@@ -0,0 +1,37 @@
/*
* Copyright 2004-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.binding.convert.converters;
/**
* Converts from a textual representation to a {@link Enum}. The text should be the enum's label.
*
* @author Scott Andrews
*/
public class StringToEnum extends StringToObject {
public StringToEnum() {
super(Enum.class);
}
protected Object toObject(String string, Class targetClass) throws Exception {
return Enum.valueOf(targetClass, string);
}
protected String toString(Object object) throws Exception {
return object.toString();
}
}

View File

@@ -29,6 +29,7 @@ import org.springframework.binding.convert.converters.StringToByte;
import org.springframework.binding.convert.converters.StringToCharacter;
import org.springframework.binding.convert.converters.StringToDate;
import org.springframework.binding.convert.converters.StringToDouble;
import org.springframework.binding.convert.converters.StringToEnum;
import org.springframework.binding.convert.converters.StringToFloat;
import org.springframework.binding.convert.converters.StringToInteger;
import org.springframework.binding.convert.converters.StringToLabeledEnum;
@@ -36,6 +37,7 @@ import org.springframework.binding.convert.converters.StringToLocale;
import org.springframework.binding.convert.converters.StringToLong;
import org.springframework.binding.convert.converters.StringToShort;
import org.springframework.core.enums.LabeledEnum;
import org.springframework.util.ClassUtils;
/**
* Default, local implementation of a conversion service. Will automatically register <i>from string</i> converters for
@@ -72,6 +74,9 @@ public class DefaultConversionService extends GenericConversionService {
addConverter(new StringToLabeledEnum());
addConverter(new ObjectToCollection(this));
addConverter(new NumberToNumber());
if (ClassUtils.isPresent("java.lang.Enum", this.getClass().getClassLoader())) {
addConverter(new StringToEnum());
}
}
protected void addDefaultAliases() {