admin
2024-07-25 47e3087067abd35e6337c011f96d2338c0bb1aae
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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 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);
    }
 
}