数据类型转化工具

public class DataTypeConvertUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(DataTypeConvertUtil.class);

    private static Map<String, Method> convertMap = Maps.newHashMap();

    private static Map<String, Class<?>> CONVERT_CLASS_MAP = Maps.newHashMap();

    static {
        try {
            Class cls = SafeParserUtil.class;
            convertMap.put("Int", cls.getMethod("parseInt", Object.class));
            convertMap.put("Long", cls.getMethod("parseLong", Object.class));
            convertMap.put("String", cls.getMethod("parseString", Object.class));
            convertMap.put("Double", cls.getMethod("parseDouble", Object.class));
            convertMap.put("Boolean", cls.getMethod("parseBoolean", Object.class));
            convertMap.put("Byte", cls.getMethod("parseByte", Object.class));
            convertMap.put("Short", cls.getMethod("parseShort", Object.class));
            convertMap.put("Float", cls.getMethod("parseFloat", Object.class));
        } catch (Exception e) {
            LOGGER.error("初始化convertMap失败", e);
        }

        try {
            CONVERT_CLASS_MAP.put("Map", Map.class);
            CONVERT_CLASS_MAP.put("List", List.class);
        } catch (Exception e) {
            LOGGER.error("初始化CONVERT_CLASS_MAP失败", e);
        }
    }

    public static Object convert(Object value, String resultType) throws ActuatorExeException {
        if (value == null) {
            return null;
        }

        Method method = convertMap.get(resultType);
        if (method != null) {
            try {
                return method.invoke(null, value);
            } catch (Exception e) {
                throw new ActuatorExeException(PlatformConstant.CONVERT_ERROR_CODE,
                        "类型转换失败, resultType:%s, value:%s", resultType, value);
            }
        }

        Class<?> clazz = CONVERT_CLASS_MAP.get(resultType);
        if (clazz != null && clazz.isAssignableFrom(value.getClass())) {
            return value;
        }

        throw new ActuatorExeException(PlatformConstant.CONVERT_ERROR_CODE, "不支持指定的类型转换, resultType: " + resultType);
    }
}

 

上一篇:Puppeteer--代码示例(3)


下一篇:3-3 Library vector Type