任意實體類轉map集合

思路

因爲程序不知道具體轉化時具體需要處理哪個實體類,所以運用反射機制。獲取到傳入的類之後,獲取該類所有方法,得到該方法的get方法(一般實體類裏只有屬性,get、set方法吧),通過get方法得到屬性的值,並且截取方法名get之後的字段,即爲參數名。

代碼

package com.nansl.util;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;

public class PojoToMap {
    public  static <T> HashMap<String,String> toMap(T t){
        HashMap<String, String> result = new HashMap<String, String>();
        Method[] methods = t.getClass().getMethods();
        try{
            for (Method method:
                    methods) {
                Class<?>[] paramClass = method.getParameterTypes();
                if (paramClass.length > 0){
                    continue;
                }
                String methodName = method.getName();
                if (methodName.startsWith("get")){
                    Object value = method.invoke(t);
                    if (value != null)
                        result.put(methodName.substring(3).toLowerCase(), String.valueOf(value));
                }
            }
        }catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        }
        result.remove("class");
        return  result;
    }
}

map轉任意pojo

這個比較麻煩,需要獲取到屬性的類型,所以我在這裏加了幾個判斷,因爲我的實體類中只有三個類型。

 public static  <T>T  mapperObj(Map map, Class<T> t) throws Exception{
        if(map==null||map.size()==0){
            return t.newInstance();
        }
        Object tobj=t.newInstance();
        System.out.println(map.keySet().size());
        for(Object key:map.keySet()){
            Field field =t.getDeclaredField((String) key);
            field.setAccessible(true);
            String type = field.getGenericType().toString();
            System.out.println("type"+type);//打印該類的所有屬性類型
            if (map.get(key) == null || map.get(key).equals("") || map.get(key).equals("null")){
                field.set(tobj,null);
                continue;
            }
            if ("class java.util.Date".equals(type)){
                System.out.println("進來了嗎");
                SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", java.util.Locale.US);
                try {
                    Date date = sdf.parse(map.get(key).toString());
                    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String time = sdf1.format(date);
                    Date time1 = sdf1.parse(time);
                    field.set(tobj, time1);
                    continue;
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            if ("int".equals(type)){
                field.set(tobj, Integer.parseInt(map.get(key).toString()));
                continue;
            }
            if ("boolean".equals(type)){
                field.set(tobj, Boolean.valueOf(map.get(key).toString()));
                continue;
            }

            field.set(tobj, map.get(key));
        }
        return (T) tobj;
    }

完整代碼

pojo:

import java.util.Date;

public class User {
    private int no;
    private String username;
    private String password;
    private Date createdate;

    public int getNo() {
        return no;
    }

    @Override
    public String toString() {
        return "User{" +
                "no=" + no +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", createdate=" + createdate +
                '}';
    }

    public void setNo(int no) {
        this.no = no;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Date getCreatedate() {
        return createdate;
    }

    public void setCreatedate(Date createdate) {
        this.createdate = createdate;
    }
}

轉化工具類:


import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class PojoToMap {
    public  static <T> HashMap<String,String> toMap(T t){
        HashMap<String, String> result = new HashMap<String, String>();
        Method[] methods = t.getClass().getMethods();
        try{
            for (Method method:
                    methods) {
                Class<?>[] paramClass = method.getParameterTypes();
                if (paramClass.length > 0){
                    continue;
                }
                String methodName = method.getName();
                if (methodName.startsWith("get")){
                    Object value = method.invoke(t);
                    if (value != null)
                        result.put(methodName.substring(3).toLowerCase(), String.valueOf(value));
                }
            }
        }catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        }
        result.remove("class");
        return  result;
    }
    public static  <T>T  mapperObj(Map map, Class<T> t) throws Exception{
        if(map==null||map.size()==0){
            return t.newInstance();
        }
        Object tobj=t.newInstance();
        System.out.println(map.keySet().size());
        for(Object key:map.keySet()){
            Field field =t.getDeclaredField((String) key);
            field.setAccessible(true);
            String type = field.getGenericType().toString();
            System.out.println("type"+type);//打印該類的所有屬性類型
            if (map.get(key) == null || map.get(key).equals("") || map.get(key).equals("null")){
                field.set(tobj,null);
                continue;
            }
            if ("class java.util.Date".equals(type)){
                System.out.println("進來了嗎");
                SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", java.util.Locale.US);
                try {
                    Date date = sdf.parse(map.get(key).toString());
                    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String time = sdf1.format(date);
                    Date time1 = sdf1.parse(time);
                    field.set(tobj, time1);
                    continue;
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            if ("int".equals(type)){
                field.set(tobj, Integer.parseInt(map.get(key).toString()));
                continue;
            }
            if ("boolean".equals(type)){
                field.set(tobj, Boolean.valueOf(map.get(key).toString()));
                continue;
            }

            field.set(tobj, map.get(key));
        }
        return (T) tobj;
    }

    public static void main(String[] args) {
        User user = new User();
        user.setCreatedate(new Date());
        user.setNo(1);
        user.setUsername("abcdefg");
        Map<String,String> map = toMap(user);
        System.out.println(map.toString());
        try {
            User user1 = mapperObj(map,User.class);
            System.out.println(user1.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章