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

com.zrun.commons.web.converter.String2EnumConvertFactory Maven / Gradle / Ivy

The newest version!
package com.zrun.commons.web.converter;

import com.zrun.commons.core.enums.BaseEnum;
import com.zrun.commons.core.utils.StringUtils;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

@Component
public class String2EnumConvertFactory implements ConverterFactory {

    @Override
    public  Converter getConverter(Class targetType) {
        return new StringToEnum<>(targetType);
    }

    @SuppressWarnings("all")
    private static class StringToEnum implements Converter {
        private Class targerType;
        public StringToEnum(Class targerType) {
            this.targerType = targerType;
        }

        @Override
        public T convert(String source) {
            if (StringUtils.isEmpty(source)) {
                return null;
            }
            return (T) String2EnumConvertFactory.getEnum(this.targerType, source);
        }
    }

    public static  Object getEnum(Class targerType, String source) {
        for (T enumObj : targerType.getEnumConstants()) {
            if (source.equals(String.valueOf(enumObj.getValue()))) {
                return enumObj;
            }
        }
        return null;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy