mercredi 20 novembre 2019

Using Field on an Object of unknown type

My application builds a cache of Field's that will be accessed later on during its lifetime. I figured creating an index of Field's would be quicker then doing a lookup every time I need to access the Field. Though, I am not seeing anyway to use the Field on a Java object.

POJO:

public class Employee {
    private String firstName;

    private String lastName;

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

Example:

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

Expected output:

Field firstName: bob
Field lastName: saget




Aucun commentaire:

Enregistrer un commentaire