需求

通过反射写一个通用的设置,可设置某个对象的某个属性为指定的值

  1. /**
  2. * 该方法可将obj对象中名为propertyName的属性的值设置为value。
  3. */
  4. public static void setProperty(Object obj, String propertyName, Object value){
  5. //TODO
  6. }

实现

  1. class ReflectTool {
  2. /**
  3. * 此方法可将obj对象中名为propertyName的属性的值设置为value。
  4. */
  5. public static void setProperty(Object obj, String propertyName, Object value) throws Exception {
  6. //获取字节码对象
  7. Class clazz = obj.getClass();
  8. //获取字段,忽略修饰符权限
  9. Field field = clazz.getDeclaredField(propertyName);
  10. //设置权限为可访问的
  11. field.setAccessible(true);
  12. field.set(obj, value);
  13. }
  14. }

测试

  1. class Student {
  2. private String name;
  3. private int age;
  4. public Student() {
  5. super();
  6. }
  7. public Student(String name, int age) {
  8. super();
  9. this.name = name;
  10. this.age = age;
  11. }
  12. public void setName(String name) {
  13. this.name = name;
  14. }
  15. public void setAge(int age) {
  16. this.age = age;
  17. }
  18. @Override
  19. public String toString() {
  20. return "Student [name=" + name + ", age=" + age + "]";
  21. }
  22. }
  1. public static void main(String[] args) throws Exception {
  2. Student s = new Student("zhangsan", 18);
  3. //Student [name=zhangsan, age=18]
  4. System.out.println(s);
  5. ReflectTool.setProperty(s, "name", "lisi");
  6. ReflectTool.setProperty(s, "age", 108);
  7. //Student [name=lisi, age=108]
  8. System.out.println(s);
  9. }