
net.sf.javaprinciples.data.transformer.spring.StringToJaxbEnumConverterFactory Maven / Gradle / Ivy
The newest version!
package net.sf.javaprinciples.data.transformer.spring;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.util.ClassUtils;
/**
* A copy of the spring class StringToEnumConverterFactory with the added bonus of handling JAXB enums
*
* @author Warwick Slade
*/
@SuppressWarnings("unchecked")
public final class StringToJaxbEnumConverterFactory implements ConverterFactory
{
public Converter getConverter(Class targetType)
{
return new StringToEnum(targetType);
}
private class StringToEnum implements Converter
{
private final Class enumType;
private final Method fromValueMethod;
public StringToEnum(Class enumType)
{
this.enumType = enumType;
fromValueMethod = ClassUtils.getMethodIfAvailable(enumType, "fromValue", new Class[]{String.class});
}
public T convert(String source)
{
if (source.length() == 0)
{
// It's an empty enum identifier: reset the enum value to null.
return null;
}
if (fromValueMethod == null)
{
return (T) Enum.valueOf(this.enumType, source.trim());
}
else
{
try
{
return (T)fromValueMethod.invoke(null, source);
}
catch (IllegalAccessException e)
{
return null;
}
catch (InvocationTargetException e)
{
return null;
}
}
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy