根据注解修改属性的值

package reflectTest;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD })
public @interface zk {
    String value() default "";
}
package reflectTest;

public class Dog {

    @zk("name")
    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;

public class RunZk {

    public static void main(String[] args) throws Exception {

        String key = "name";
        String chgValue = "xxxxxx";
        // 性别: 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) {
            if (f.isAnnotationPresent(zk.class)) {
                zk anno = f.getAnnotation(zk.class);
                if (anno.value().equals(key)) {
                    System.out.println(f.getName());
                    Field nameField = clazz.getDeclaredField(f.getName());// 获取私有成员变量:name
                    nameField.setAccessible(true);// 设置操作权限为true
                    nameField.set(dog, chgValue);
                }
            }
        }
        System.out.println(dog.toString());
    }
}

有追求,才有动力!

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

by wujf

mail:921252375@qq.com

原文地址:https://www.cnblogs.com/wujf/p/9122626.html