Map of field name as key and value as value

Viewed 35

I would like to create Map<String, Double> when as keys there will be names of declared fields of class, and as value - value of that field: For example:

class Car {
    private double price;
    private long vmax;
}
Map<{price, 100000}, {vmax, 200}>

I know how to "iter" by fields but I can not get that value:

public Map<String, Double> convert(Object object) {
    Map<String, Double> parameters = new HashMap<>();
    for (Field declaredField : object.getClass().getDeclaredFields()) {
       declaredField.setAccessible(true);
       parameters.put(declaredField.getName(), (Double) declaredField.get(object));
    }
    return parameters;
}
1 Answers

The error you experience is ClassCastException:

Exception in thread "main" java.lang.ClassCastException: class java.lang.Long cannot be cast to class java.lang.Double

This is obvious as you try to cast long vmax into Double through the following snippet:

(Double) declaredField.get(object)

Though the declared field name is String, the field's value cannot be determined and casting is required. The wanted type is never guaranteed. In the case of double price, it can be cast into Double, but it is not for long vmax.

You want to change the map generics and casting to Map<String, Number> or rather Map<String, Object> that would be safer.

public static Map<String, Object> convert(Object object) throws IllegalAccessException {
    Map<String, Object> parameters = new HashMap<>();
    for (Field declaredField : object.getClass().getDeclaredFields()) {
        declaredField.setAccessible(true);
        parameters.put(declaredField.getName(), declaredField.get(object));
    }
    return parameters;
}

For sample instance new Car(15d, 25L), the map would result as {price=15.0, vmax=25}.

Related