通过反射获取某个对象属性是否存在,并获取对象值

    @SneakyThrows
    public static void main(String[] args) {

        User user = new User("张三", 10);
        // 获取指定属性名的值
        String propertyName = "name2";
        Field[] fields = user.getClass().getDeclaredFields();
        // 输出属性名
        Boolean flag = false;
        for (Field field : fields) {
            if (field.getName().equals(propertyName)) {
                flag = true;
                field.setAccessible(true);
                Object value = field.get(user);
                System.out.println(value);
            }
        }
        if (!flag) {
            System.out.println(user.getClass().getSimpleName() + ":对象不存在属性:" + propertyName );
        }
    }

    static class User {
        private String name;
        private int age;

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

        public String getName() {
            return name;
        }

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

        public Integer getAge() {
            return age;
        }

        public User(String name, int age) {
            this.name = name;
            this.age = age;
        }
    }

你可能感兴趣的:(java,前端,开发语言)