根据对象中字段属性值,动态java反射调用相应的get方法

本文介绍如何利用Java反射机制动态地从对象中获取指定字段的值。通过实例演示了将商品对象GoodsVO的各个字段及其对应的get方法返回值存储到Map中的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

根据对象中字段属性值,动态调用相应的get方法

#### 举个例子,把对象GoodsVO中的字段作为key, get方法作为value,全部存放在Map中.

//商品对象
public class GoodsVO {

    /**
     * 品牌ID
     */
    private Long brandId;

    /**
     * 品牌名称
     */
    private String brandName;

    /**
     * 商品ID
     */
    private Long goodsId;

    /**
     * 商品标签
     */
    private List<String> goodsTagList;

    /**
     * 库存
     */
    private Integer actualStore;

    /**
     * 状态 0 下架 1 上架
     */
    private Integer status;

    public GoodsVO() {
    }

    public GoodsVO(String brandName, Long brandId,Long goodsId,  Integer actualStore, Integer status, List<String> goodsTagList) {
        this.brandName = brandName;
        this.goodsId = goodsId;
        this.brandId = brandId;
        this.actualStore = actualStore;
        this.status = status;
        this.goodsTagList = goodsTagList;
    }
set/get。。。。
}

实际情况我们可以采用笨方法,一个一个的put到map中,但是这不是我们今天想要学习的。

采用java反射实现

/**
 * @author zhanghuilong
 * @desc
 * @since 2018/06/12
 */
public class Test {

    public static void main(String[] args) throws IllegalAccessException, InstantiationException {

        GoodsVO goodsVO = new GoodsVO("苹果",1L,100L,101, 1,asList("����-Apple","果粉","Mac系列\n"));
        Class<?> aClass = GoodsVO.class;
        Field[] fields = aClass.getDeclaredFields();
        Map<Object, Object> map = new HashMap<>();
        for (Field field  : fields){
            map.put(field.getName() , getResult(field.getName() , goodsVO));
        }

        System.out.println(JSON.toJSONString(map));
    }


    private static Object getResult(Object fieldName, GoodsVO goodsVO) {
        try {
            Class<?> aClass = goodsVO.getClass();
            Field declaredField = aClass.getDeclaredField(fieldName.toString());
            declaredField.setAccessible(true);
            PropertyDescriptor pd = new PropertyDescriptor(declaredField.getName(), aClass);
            Method readMethod = pd.getReadMethod();

            return readMethod.invoke(goodsVO);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IntrospectionException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }
}

输出结果:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值