利用反射将Map转成JavaBean(属性值均为private,且包含Long类型属性)

来源:互联网 发布:上海嵌入式软件开发 编辑:程序博客网 时间:2024/06/05 22:49

1.实体类(所有属性均为private,且存在Long类型)

public class Test {    private String name;    private Long id;    private int age;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public Long getId() {        return id;    }    public void setId(Long id) {        this.id = id;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }}

2.转换方法:

    /**     * 将Map转换为JavaBean对象     * @param c class对象     * @param map     * @return     * @throws IllegalAccessException     * @throws InstantiationException     */    public static Object convertMap(Class c,Map<String,Object> map) throws IllegalAccessException, InstantiationException {        Object o = c.newInstance();        Field[] fileds = c.getDeclaredFields();        for(Field field : fileds){            //取消默认 Java 语言访问控制检查的能力 即允许对private属性进行直接赋值或获取            field.setAccessible(true);            if(field.getType() == Long.class){//Long类型需手动转换,否则报类型转换出错                field.set(o,((Integer)map.get(field.getName())).longValue());            }else{                field.set(o,map.get(field.getName()));            }        }        return o;    }

3.测试方法:

 public static void main(String[] args) {        Map<String,Object> map = new HashMap<>();        map.put("name","张三");        map.put("age",23);        map.put("id",1231);        try {            convertMap(Test.class,map);        } catch (IllegalAccessException e) {            e.printStackTrace();        } catch (InstantiationException e) {            e.printStackTrace();        }    }

亲测可用,菜鸟一名,对人家写好的代码出错不知道从何下手,只好重写。。。。

阅读全文
0 0
原创粉丝点击