数据类型转化工具

旧城等待, 2022-10-29 01:57 272阅读 0赞
  1. public class DataTypeConvertUtil {
  2. private static final Logger LOGGER = LoggerFactory.getLogger(DataTypeConvertUtil.class);
  3. private static Map<String, Method> convertMap = Maps.newHashMap();
  4. private static Map<String, Class<?>> CONVERT_CLASS_MAP = Maps.newHashMap();
  5. static {
  6. try {
  7. Class cls = SafeParserUtil.class;
  8. convertMap.put("Int", cls.getMethod("parseInt", Object.class));
  9. convertMap.put("Long", cls.getMethod("parseLong", Object.class));
  10. convertMap.put("String", cls.getMethod("parseString", Object.class));
  11. convertMap.put("Double", cls.getMethod("parseDouble", Object.class));
  12. convertMap.put("Boolean", cls.getMethod("parseBoolean", Object.class));
  13. convertMap.put("Byte", cls.getMethod("parseByte", Object.class));
  14. convertMap.put("Short", cls.getMethod("parseShort", Object.class));
  15. convertMap.put("Float", cls.getMethod("parseFloat", Object.class));
  16. } catch (Exception e) {
  17. LOGGER.error("初始化convertMap失败", e);
  18. }
  19. try {
  20. CONVERT_CLASS_MAP.put("Map", Map.class);
  21. CONVERT_CLASS_MAP.put("List", List.class);
  22. } catch (Exception e) {
  23. LOGGER.error("初始化CONVERT_CLASS_MAP失败", e);
  24. }
  25. }
  26. public static Object convert(Object value, String resultType) throws ActuatorExeException {
  27. if (value == null) {
  28. return null;
  29. }
  30. Method method = convertMap.get(resultType);
  31. if (method != null) {
  32. try {
  33. return method.invoke(null, value);
  34. } catch (Exception e) {
  35. throw new ActuatorExeException(PlatformConstant.CONVERT_ERROR_CODE,
  36. "类型转换失败, resultType:%s, value:%s", resultType, value);
  37. }
  38. }
  39. Class<?> clazz = CONVERT_CLASS_MAP.get(resultType);
  40. if (clazz != null && clazz.isAssignableFrom(value.getClass())) {
  41. return value;
  42. }
  43. throw new ActuatorExeException(PlatformConstant.CONVERT_ERROR_CODE, "不支持指定的类型转换, resultType: " + resultType);
  44. }
  45. }

发表评论

表情:
评论列表 (有 0 条评论,272人围观)

还没有评论,来说两句吧...

相关阅读