如何在一个对象使用反射访问一个字段的值(How to access a field's va

2019-08-01 06:11发布

我的问题:如何克服IllegalAccessException访问使用反射对象的字段的值。

扩展:我想了解反射,使我的一些项目更通用。 我遇到一个IllegalAccessException试图调用时field.getValue(object)来获得在该对象字段的值。 我能得到的名称和类型就好了。

如果我更改从申报privatepublic那么这工作得很好。 但是,在努力遵循封装的“规则”,我不希望这样做。 任何帮助将不胜感激! 谢谢!

我的代码:

package main;

import java.lang.reflect.Field;

public class Tester {

  public static void main(String args[]) throws Exception {
    new Tester().reflectionTest();
  }

  public void reflectionTest() throws Exception {
    Person person = new Person("John Doe", "555-123-4567", "Rover");
    Field[] fields = person.getClass().getDeclaredFields();
    for (Field field : fields) {
      System.out.println("Field Name: " + field.getName());
      System.out.println("Field Type: " + field.getType());
      System.out.println("Field Value: " + field.get(person));
      //The line above throws: Exception in thread "main" java.lang.IllegalAccessException: Class main.Tester can not access a member of class main.Tester$Person with modifiers "private final"
    }
  }

  public class Person {

    private final String name;
    private final String phoneNumber;
    private final String dogsName;

    public Person(String name, String phoneNumber, String dogsName) {
      this.name = name;
      this.phoneNumber = phoneNumber;
      this.dogsName = dogsName;
    }
  }
}

输出:

run:
Field Name: name
Field Type: class java.lang.String
Exception in thread "main" java.lang.IllegalAccessException: Class main.Tester can not access a member of class main.Tester$Person with modifiers "private final"
    at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:95)
    at java.lang.reflect.AccessibleObject.slowCheckMemberAccess(AccessibleObject.java:261)
    at java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:253)
    at java.lang.reflect.Field.doSecurityCheck(Field.java:983)
    at java.lang.reflect.Field.getFieldAccessor(Field.java:927)
    at java.lang.reflect.Field.get(Field.java:372)
    at main.Tester.reflectionTest(Tester.java:17)
    at main.Tester.main(Tester.java:8)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)

Answer 1:

在你get一个私有字段,你需要调用setAccessible(true); 上的对应字段:

for (Field field : fields) {
    field.setAccessible(true); // Additional line
    System.out.println("Field Name: " + field.getName());
    System.out.println("Field Type: " + field.getType());
    System.out.println("Field Value: " + field.get(person));
}


Answer 2:

默认情况下,你都读不准非公开领域,而是简单地调用field.setAccessible(true); 将允许访问。 换句话说,你的代码应该说

for (Field field : fields) {
  field.setAccessible(true);
  // ...
}


文章来源: How to access a field's value in an object using reflection