• 通过反射改变对象的属性


    package ReflectTest;
    
    public class Dog {
    
        private final String name;
        private final int sex;
        private final int weight;
        private final String type;
    
        public Dog(String name, int sex, int weight, String type) {
            this.name = name;
            this.sex = sex;
            this.weight = weight;
            this.type = type;
        }
    
        public String getName() {
            return name;
        }
    
        public int getSex() {
            return sex;
        }
    
        public int getWeight() {
            return weight;
        }
    
        public String getType() {
            return type;
        }
    
        @Override
        public String toString() {
            return "{"name":"" + name + "","sex":"" + sex + "","weight":"" + weight + "","type":"" + type + ""} ";
        }
    }
    package ReflectTest;
    
    import java.lang.reflect.Field;
    import java.lang.reflect.Modifier;
    
    public class Run {
    
        public static void main(String[] args) throws Exception {
            // 性别: 0:母, 1:公
            Dog dog = new Dog("点点", 0, 25, "哈士奇");
            System.out.println(dog.toString());
            Class<? extends Dog> clazz = dog.getClass();// 获取到对象对应的class对象
            Field[] fields = clazz.getDeclaredFields();//
            for (Field f : fields) {
                String fileName = f.getName();
                int m = f.getModifiers();
                String mStr = Modifier.toString(m);
                System.out.println(fileName + " 属性:" + mStr);
            }
    
            // 把上面已经创建好的狗狗的名字改为:大大
            Field nameField = clazz.getDeclaredField("name");// 获取私有成员变量:name
            nameField.setAccessible(true);// 设置操作权限为true
            nameField.set(dog, "大大");
            Field typeField = clazz.getDeclaredField("type");
            typeField.setAccessible(true);
            typeField.set(dog, "金毛");
            System.out.println(dog.toString());
        }
    
    }

    有追求,才有动力!

    向每一个软件工程师致敬!

    by wujf

    mail:921252375@qq.com

  • 相关阅读:
    react 和 vue 的优缺点总结
    解决js小数求和出现多位小数问题
    同步循环发请求用promise
    hook中ref使用
    只能输入数字和保留三位的小树
    react添加右键点击事件
    redux
    深拷贝和浅拷贝区别及概念
    pointer-events的css属性。使用该属性可以决定是否能穿透绝对定位元素去触发下面元素的某些行为
    React 使用link在url添加参数(url中不可见)
  • 原文地址:https://www.cnblogs.com/wujf/p/9122268.html
Copyright © 2020-2023  润新知