在未知类型的对象上使用字段

时间:2019-11-20 17:41:53

标签: java reflection

我的应用程序构建了Field的缓存,以后将在其生命周期内对其进行访问。我认为创建Field的索引比每次访问Field的查询都要快。不过,我仍然看不到在Java对象上使用Field

POJO:

public class Employee {
    private String firstName;

    private String lastName;

    Employee(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
}

示例:

public static void main(String[] args) throws IOException {
    Map<String, Field> fields = new HashMap<>();

    for (Field field : Employee.class.getDeclaredFields()) {
        fields.add(field.getName(), field);
    }

    Object employee = new Employee("bob", "saget");

    fields.entrySet().forEach((entry) -> {
        // Showing intent, obviously getFieldValue doesn't exist
        System.out.println("Field " + entry.getKey() + ": " + employee.getClass().getFieldValue(entry.getValue());
    });
}

预期输出:

Field firstName: bob
Field lastName: saget

1 个答案:

答案 0 :(得分:0)

我不确定您为什么要使用反射,但这会给您您所说的“预期输出”

public class Employee {
    private String firstName;

    private String lastName;

    Employee(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public static void main(String[] args) throws IOException {
        Map<String, Field> fields = new HashMap<>();
        for (Field field : Employee.class.getDeclaredFields()) {
            fields.put(field.getName(), field);
        }
        Object employee = new Employee("bob", "saget");
        fields.entrySet().forEach((entry) -> {
            try {
                System.out.println("Field " + entry.getKey() + ": " + entry.getValue().get(employee));
            } catch (IllegalArgumentException | IllegalAccessException e) {
            }
        });
    }
}