Java内省beans包的使用

内省(Introspector)是Java语言对Bean类属性,事件的一种缺省处理方法

在接口调用中常常需要对参数进行封装到map中,这时Introspector就派上了用场。
代码如下:

package com.daling.util;

import com.daling.bean.User;
import com.google.common.collect.Maps;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.Map;

/**
 * @author tanhq
 */
public class BeanProcessUtil {

    public static Map<String, Object> transBean2Map(Object obj, Map<String, Object> map) throws Exception {
        //实体类不能为空
        if (obj == null) {
            return map;
        }
        try {
            // 在 Java Bean 上进行内省,了解其所有属性、公开的方法和事件
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
            // 获得 beans PropertyDescriptor
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                // 父类FeatureDescriptor的方法,获得此特性的编程名称
                String key = property.getName();
                // 过滤class属性
                if (!key.equals("class")) {
                    // 得到property对应的getter方法
                    Method getter = property.getReadMethod();
                    // 调用指定对象的指定方法
                    Object value = getter.invoke(obj);
                    map.put(key, value == null ? "" : value);
                }
            }
        } catch (Exception e) {
            throw new Exception("将实体类转换成Map过程异常");
        }
        return map;
    }
}

测试代码:

public static void main(String[] args) {
        Map<String, Object> map = Maps.newHashMap();
        User user = new User();
        user.setDate(new Date());
        user.setId(1);
        user.setAge(26);
        user.setName("tanhq");
        user.setReceiveAddress("北京朝阳");
        try {
            map = transBean2Map(user, map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(map);
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值