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();
        }
    }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM