Java反射获取对象的属性值

当知道某个类,想获取类上的某个属性的值时,有时会用到Java的反射机制,如下参考:
/**
 * 反射获取对象的属性值
 * @param object 对象(要遍历的对象)
 * @param targetFieldName 属性名
 * @return 属性值
 */
private static Object getFieldValueByObject(Object object, String targetFieldName) {
    Object result = null;
    Class objClass = object.getClass();
    Field[] fields = objClass.getDeclaredFields();
    for (Field field : fields) {
        String currentFieldName = "";
        try {
            boolean hasJsonProperty = field.isAnnotationPresent(JsonProperty.class);
            if (hasJsonProperty) {
                currentFieldName = field.getAnnotation(JsonProperty.class).value();
            } else {
                currentFieldName = field.getName();
            }
            if (currentFieldName.toUpperCase().equals(targetFieldName.toUpperCase())) {
                //设置属性的可访问性
                field.setAccessible(true);
                result = field.get(object);
                return result;
            }
        } catch (SecurityException e) {
            // 安全性异常
            throw new RuntimeException("获取对象的属性值安全性异常:" + e.getMessage());
        } catch (IllegalArgumentException e) {
            // 非法参数
            throw new RuntimeException("获取对象的属性值非法参数异常:" + e.getMessage());
        } catch (IllegalAccessException e) {
            // 无访问权限
            throw new RuntimeException("获取对象的属性值无访问权限异常:" + e.getMessage());
        }
    }
    return result;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值