From 47e3087067abd35e6337c011f96d2338c0bb1aae Mon Sep 17 00:00:00 2001 From: admin <weikou2014> Date: 星期四, 25 七月 2024 13:39:31 +0800 Subject: [PATCH] 优化自动化代码 --- src/main/java/org/yeshi/utils/annotation/MapUtil.java | 82 ++++++++++++++++++++++++++++------------- 1 files changed, 56 insertions(+), 26 deletions(-) diff --git a/src/main/java/org/yeshi/utils/annotation/MapUtil.java b/src/main/java/org/yeshi/utils/annotation/MapUtil.java index 6c8d79a..ecb8f87 100644 --- a/src/main/java/org/yeshi/utils/annotation/MapUtil.java +++ b/src/main/java/org/yeshi/utils/annotation/MapUtil.java @@ -1,36 +1,66 @@ package org.yeshi.utils.annotation; +import com.google.gson.Gson; +import net.sf.json.JSONObject; +import org.yeshi.utils.StringUtil; + +import java.io.UnsupportedEncodingException; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.util.Properties; public class MapUtil { - public static Object parseMap(Class<?> clazz, Properties ps) { - System.out.println(clazz.getName()); - Object target = null; - try { - Class clz = Class.forName(clazz.getName()); - target = clz.newInstance(); - } catch (Exception e) { - e.printStackTrace(); - } - Field[] fields = clazz.getDeclaredFields(); - for (Field fd : fields) { - fd.setAccessible(true); - Annotation[] as = fd.getAnnotations(); - for (Annotation a : as) { - if (a instanceof Map) { - Map c = (Map) a; - try { - fd.set(target, new String(ps.getProperty(c.value()).getBytes("ISO-8859-1"), "UTF-8")); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - } - return target; - } + public static Object parseMap(Class<?> clazz, Properties ps) { + System.out.println(clazz.getName()); + Object target = null; + try { + Class clz = Class.forName(clazz.getName()); + target = clz.newInstance(); + } catch (Exception e) { + e.printStackTrace(); + } + Field[] fields = clazz.getDeclaredFields(); + for (Field fd : fields) { + fd.setAccessible(true); + Annotation[] as = fd.getAnnotations(); + for (Annotation a : as) { + if (a instanceof Map) { + Map c = (Map) a; + try { + fd.set(target, new String(ps.getProperty(c.value()).getBytes("ISO-8859-1"), "UTF-8")); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } + return target; + } + + + public static Object parseMapByJson(Class<?> clazz, Properties ps, String encoding) { + if (StringUtil.isNullOrEmpty(encoding)) { + encoding = "ISO-8859-1"; + } + JSONObject json = new JSONObject(); + Field[] fields = clazz.getDeclaredFields(); + for (Field fd : fields) { + fd.setAccessible(true); + Annotation[] as = fd.getAnnotations(); + for (Annotation a : as) { + if (a instanceof Map) { + Map c = (Map) a; + try { + json.put(fd.getName(), new String(ps.getProperty(c.value()).getBytes(encoding), "UTF-8")); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + + } + } + } + return new Gson().fromJson(json.toString(), clazz); + } } -- Gitblit v1.8.0