All Downloads are FREE. Search and download functionalities are using the official Maven repository.

message.mvc.convert.EnumCodeConverterFactory Maven / Gradle / Ivy

There is a newer version: 2.5.9
Show newest version
package message.mvc.convert;

import message.base.bean.Codeable;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.ConditionalConverter;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;

/**
 * spring mvc将传递的参数转换成枚举.
 *
 * @author sunhao([email protected])
 * @version V1.0
 * @createTime 2014-12-17 20:23
 */
public class EnumCodeConverterFactory implements ConverterFactory>, ConditionalConverter {
    @Override
    public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
        Class clazz = targetType.getType();
        return Enum.class.isAssignableFrom(clazz) && Codeable.class.isAssignableFrom(clazz);
    }

    @Override
    public > Converter getConverter(Class targetType) {
        if(!Codeable.class.isAssignableFrom(targetType)){
            return null;
        }

        return new ValueToEnum(targetType);
    }

    private class ValueToEnum & Codeable> implements Converter {
        private T[] enums;

        public ValueToEnum(Class enumType) {
            this.enums = enumType.getEnumConstants();
        }

        @Override
        public T convert(String source) {
            for (T em : enums) {
                if (em.getCode().equals(source)) {
                    return em;
                }
            }
            return null;
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy