首页 > 解决方案 > 在未知类型的对象上使用字段

问题描述

我的应用程序构建了一个Field's 的缓存,稍后将在其生命周期内访问该缓存。我认为创建Field's 的索引会比每次需要访问Field. 不过,无论如何我都没有看到Field在 Java 对象上使用。

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

标签: javareflection

解决方案


推荐阅读