记一次根据实体类的属性名来给属性名赋值,根据属性名得到属性名的值,其中使用的是JsonProperty属性名

//  此处是根据属性名来给属性名赋值的方法,本人亲自测试过可用

/**
 * 
 * @param key  属性名
 * @param value  属性名的值
 * @param object  属性的实体类
 */
public static void getValues(String key, String value, Object object) {
    Object returnStr = null;
    try {
        Field[] fields = object.getClass().getDeclaredFields();
        for (Field field: fields) {
            field.setAccessible(true);
            returnStr = field.get(object);
            if (field.getAnnotation(JsonProperty.class) != null) {
                JsonProperty annotation = ((JsonProperty) field.getAnnotation(JsonProperty.class));
                if (annotation != null) {
                    System.out.println(annotation + "");
                    String jsonPropertyValue = annotation.value();
                    if (key.equals(jsonPropertyValue)) {
                        field.set(object, value);
                        break;
                    }
                }
            }else{
                String fieldName = field.getName();
                if(key.equals(fieldName)){
                   field.set(object,value);
                   break;
                }
             }
        }
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    }
}

-- 根据属性名得到属性名的值的方法,本人亲自测试过可用

/**
 * 通过属性名获取属性的值
 *
 * @param key   属性名
 * @param object 对象
 */
public static Object getValues(String key, Object object) throws IllegalAccessException{
    //  Object returnStr = null;
    //try {
    java.lang.reflect.Field[] fields = object.getClass().getDeclaredFields();
    for (Field field : fields) {
        field.setAccessible(true);
        if (field.getAnnotation(JsonProperty.class) != null) {
            JsonProperty annotation = ((JsonProperty) field.getAnnotation(JsonProperty.class));
            if (annotation != null) {
                String jsonPropertyValue = annotation.value();
                if (key.equals(jsonPropertyValue)) {
                    Object values = field.get(object);
                    return values;
                }
            }
        }else{
            //获取的不是@jsonproperty的属性名称
            String fieldName = field.getName();
             if (key.equals(fieldName)) {
                Object values = field.get(object);
                return values;
            }
        }
    }
    return null;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值