java实现map和object互转的三种方法

来源:互联网 发布:美剧学口语 知乎 编辑:程序博客网 时间:2024/05/19 19:56

http://www.open-open.com/code/view/1423280939826


package com.test.maptoobject;


import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;


import com.test.mongodb.User;



public class MapAndObject {


    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        // BaseCommandController
        Map<String, Object> userMap=new HashMap<>();
        userMap.put("age", 12);
        userMap.put("className", "class1111");
        User user=new User();
        user.setAge(23);
        user.setclassName("userclass");
        try {
            System.out.println("--AAA------------");
            System.out.println(A.mapToObject(userMap, User.class));
            System.out.println(A.objectToMap(user));
            System.out.println("--BBBB------------\n");
            System.out.println(B.mapToObject(userMap, User.class));
            System.out.println(B.objectToMap(user));
            System.out.println("---CCC-----------\n");
            System.out.println(C.mapToObject(userMap, User.class));
            System.out.println(C.objectToMap(user));
            System.out.println("--------------");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }
}


/**
 * 使用org.apache.commons.beanutils进行转换
 */
class A {
    public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
        if (map == null)
            return null;
        Object obj = beanClass.newInstance();
        org.apache.commons.beanutils.BeanUtils.populate(obj, map);
        return obj;
    }


    public static Map<?, ?> objectToMap(Object obj) {
        if (obj == null)
            return null;
        return new org.apache.commons.beanutils.BeanMap(obj);
    }
}


/**
 * 使用Introspector进行转换
 */
class B {


    public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
        if (map == null)
            return null;
        Object obj = beanClass.newInstance();
        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor property : propertyDescriptors) {
            Method setter = property.getWriteMethod();
            System.out.println("writeMethod:" + setter + ",getName:" + property.getName());
            if (setter != null) {
                setter.invoke(obj, map.get(property.getName()));
            }
        }


        return obj;
    }


    public static Map<String, Object> objectToMap(Object obj) throws Exception {
        if (obj == null)
            return null;


        Map<String, Object> map = new HashMap<String, Object>();


        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor property : propertyDescriptors) {
            String key = property.getName();


            if (key.compareToIgnoreCase("class") == 0) {
                continue;
            }
            Method getter = property.getReadMethod();
            System.out.println("key:" + key + ",getter:" + getter);
            Object value = getter != null ? getter.invoke(obj) : null;
            map.put(key, value);
        }


        return map;
    }


}


/**
 * 使用reflect进行转换
 */
class C {


    public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
        if (map == null)
            return null;
        Object obj = beanClass.newInstance();
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            int mod = field.getModifiers();
            if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                continue;
            }
            field.setAccessible(true);
            field.set(obj, map.get(field.getName()));
        }
        return obj;
    }


    public static Map<String, Object> objectToMap(Object obj) throws Exception {
        if (obj == null) {
            return null;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        Field[] declaredFields = obj.getClass().getDeclaredFields();
        for (Field field : declaredFields) {
            field.setAccessible(true);
            map.put(field.getName(), field.get(obj));
        }
        return map;
    }

}


package com.test.mongodb;


import java.io.Serializable;


import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;


import com.google.common.base.Objects;
import com.itextpdf.text.pdf.PdfStructTreeController.returnType;


@Document(collection="users")
public class User implements Serializable{


    /**  */
    private static final long serialVersionUID = 6687575755665134766L;
    
    @Field(value="_id")
    private String _id;


    @Field(value="age")
    private int age;
    
    @Field(value="name")
    private String name;
    
    @Field(value="sex")
    private String sex;
    
    
    private transient String className;


    public String getSex() {
        return sex;
    }


    public void setSex(String sex) {
        this.sex = sex;
    }


    public int getAge() {
        return age;
    }


    public void setAge(int age) {
        this.age = age;
    }


    public String getName() {
        return name;
    }


    public void setName(String name) {
        this.name = name;
    }


    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + age;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }


//    public int HashCode2(){
//        Field[] fields=this.getClass().getDeclaredFields();
//        for(Field field:fields){
//            
//        }
//        return Objects.hashCode(age,name);
//    }
//    
    public boolean equals2(Object obj){
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        User other = (User) obj;
        return Objects.equal(this.age, other.getAge())
                &&Objects.equal(this.getName(), other.getName());
        
    }
    
    public String toString2() {
        return Objects.toStringHelper(this).toString();//只能得到类名
    }


    
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        User other = (User) obj;
        if (age != other.age)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }


    @Override
    public String toString() {
//       return ToStringBuilder.reflectionToString(this,ToStringStyle.SHORT_PREFIX_STYLE);//transient不处理
        return new StringBuilder().append("\n[_id"+_id).append(",name:"+name)
                .append(",sex:"+sex).append(",classname:"+className)
                .append(",serialVersionUID:"+serialVersionUID).toString();
    }


    /**
     * @return the className
     */
    public String getclassName() {
        return className;
    }


    /**
     * @param className the className to set
     */
    public void setclassName(String className) {
        this.className = className;
    }


}


0 0
原创粉丝点击