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

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

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

//商品对象
public class GoodsVO {

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

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

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

    /**
     * 商品标签
     */
    private List goodsTagList;

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

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

    public GoodsVO() {
    }

    public GoodsVO(String brandName, Long brandId,Long goodsId,  Integer actualStore, Integer status, List 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 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;
    }
}

输出结果:
根据对象中字段属性值,动态java反射调用相应的get方法_第1张图片

你可能感兴趣的:(java,反射)