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

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
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值