按要求完成下面两个方法的方法体

  1. 写一个方法,此方法可将obj对象中名为propertyName的属性的值设置为value.
    public void setProperty(Object obj, String propertyName, Object value){}
  2. 写一个方法,此方法可以获取obj对象中名为propertyName的属性的值
    public Object getProperty(Object obj, String propertyName){}

使用反射技术实现。 使用Field对象给成员变量赋值、取值

public class Student {
    
    
    private int age;
    private String name;

    public Student() {
    
    
    }

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

    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;
    }

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


public class Test {
    
    
    public static void main(String[] args) throws Exception {
    
    
        Student student = new Student(18, "王宝强");

        setProperty(student, "age", 21);

        System.out.println(student);

        Object obj = getProperty(student, "name");

        System.out.println(obj);
    }

    public static void setProperty(Object obj, String propertyName, Object value) throws Exception {
    
    

        Class clazz = obj.getClass();

        Field propertyNameField = clazz.getDeclaredField(propertyName);

        propertyNameField.setAccessible(true);

        propertyNameField.set(obj, value);

    }

    public static Object getProperty(Object obj, String propertyName) throws Exception {
    
    
        Class clazz = obj.getClass();

        Field propertyNameField = clazz.getDeclaredField(propertyName);

        propertyNameField.setAccessible(true);

        return propertyNameField.get(obj);
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_52067329/article/details/115448503