Java 根据字段名称获取字段值, 根据字段名称设置字段值

定义测试对象

public class User {

    private int age;
    private String name;
    private Date birthday;
    private boolean adult;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public boolean isAdult() {
        return adult;
    }

    public void setAdult(boolean adult) {
        this.adult = adult;
    }

    @Override
    public String toString() {
        return "User{" +
                "age=" + age +
                ", name='" + name + '\'' +
                ", birthday=" + birthday +
                ", adult=" + adult +
                '}';
    }
}

测试代码

    private static Object getValue(Object object, String fieldName) {
        try {
            Field field = object.getClass().getDeclaredField(fieldName);
            field.setAccessible(true);
            return field.get(object);
        } catch (NoSuchFieldException e) {

        } catch (IllegalAccessException e) {

        }
        return null;
    }

    public static <T> void setValue(T t, String fieldName, Object value) {
        try {
            Class<T> tClass = (Class<T>) t.getClass();
            Field declaredField = tClass.getDeclaredField(fieldName);
            declaredField.setAccessible(true);
            declaredField.set(t, value);
        } catch (NoSuchFieldException e) {

        } catch (SecurityException e) {

        } catch (IllegalArgumentException e) {

        } catch (IllegalAccessException e) {

        }
    }


    public static void main(String[] args){
        User user = new User();
        user.setAge(11);
        user.setBirthday(new Date());
        user.setAdult(false);
        user.setName("张三");

        Object age = getValue(user, "age");
        Object name = getValue(user, "name");
        Object birthday = getValue(user, "birthday");
        Object adult = getValue(user, "adult");

        User copyUser = new User();
        setValue(copyUser, "age", age);
        setValue(copyUser, "name", name);
        setValue(copyUser, "birthday", birthday);
        setValue(copyUser, "adult", adult);

        System.out.println(user);
        System.out.println(copyUser);

    }

运行man函数结果

User{age=11, name='张三', birthday=Wed Jan 13 10:34:39 CST 2021, adult=false}
User{age=11, name='张三', birthday=Wed Jan 13 10:34:39 CST 2021, adult=false}

补充:上述根据属性字段获取属性值的方法只能获取当前类中的属性值,无法获取父类的属性值,可以使用如下方法获取父类中的属性值

    public static Object getValueContainParent(Object object, String fieldName) {
        Class clazz = object.getClass();
        while (clazz != null) {
            Field[] declaredFields = clazz.getDeclaredFields();
            for (Field declaredField : declaredFields) {
                if (declaredField.getName().equals(fieldName)) {
                    declaredField.setAccessible(true);
                    try {
                        return declaredField.get(object);
                    } catch (IllegalAccessException e) {
                        logger.error("获取对象属性失败,参数错误 -- 类中:{} 属性:{}", object.getClass().toString(), fieldName, e);
                    }
                }
            }
            clazz = clazz.getSuperclass();
        }
        return null;
    }

  • 0
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

起个昵称不容易1

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值