JAVA 获取/设置bean的某个属性值

public class test{
    // 设置bean的某个属性值
    public static void setProperty(MaterialPriceLineVO materialPriceLineVO, String fieldName, String value) throws Exception {
        // 获取bean的某个属性的描述符
        PropertyDescriptor propDesc = new PropertyDescriptor(fieldName, MaterialPriceLineVO.class);
        // 获得用于写入属性值的方法
        Method methodSetUserName = propDesc.getWriteMethod();
        // 写入属性值
        methodSetUserName.invoke(materialPriceLineVO, value);
    }

    // 获取bean的某个属性值
    public static String getStringProperty(MaterialPriceLineVO materialPriceLineVO, String fieldName) throws Exception {
        // 获取Bean的某个属性的描述符
        PropertyDescriptor proDescriptor = new PropertyDescriptor(fieldName, MaterialPriceLineVO.class);
        // 获得用于读取属性值的方法
        Method methodGet = proDescriptor.getReadMethod();
        // 读取属性值
        Object objValue = methodGet.invoke(materialPriceLineVO);
        if (ObjectUtils.isEmpty(objValue) || "null".equals(objValue)){
            return null;
        }else {
            return objValue.toString();
        }
    }

    public static String getIntegerProperty(MaterialPriceLineVO materialPriceLineVO, String fieldName) throws Exception {
        // 获取Bean的某个属性的描述符
        PropertyDescriptor proDescriptor = new PropertyDescriptor(fieldName, MaterialPriceLineVO.class);
        // 获得用于读取属性值的方法
        Method methodGet = proDescriptor.getReadMethod();
        // 读取属性值
        Object objValue = methodGet.invoke(materialPriceLineVO);
        if (ObjectUtils.isEmpty(objValue) || "null".equals(objValue)){
            return null;
        }else {
            return objValue.toString();
        }
    }

    public static String getBigDecimalProperty(MaterialPriceLineVO materialPriceLineVO, String fieldName) throws Exception {
        // 获取Bean的某个属性的描述符
        PropertyDescriptor proDescriptor = new PropertyDescriptor(fieldName, MaterialPriceLineVO.class);
        // 获得用于读取属性值的方法
        Method methodGet = proDescriptor.getReadMethod();
        // 读取属性值
        Object objValue = methodGet.invoke(materialPriceLineVO);
        if (ObjectUtils.isEmpty(objValue) || "null".equals(objValue)){
            return null;
        }else {
            return objValue.toString();
        }
    }
}

 

posted @ 2021-09-02 17:39  哎丫丫呀喂  阅读(1128)  评论(0编辑  收藏  举报