How do I cast a HashMap to a concrete class?
The second is not possible because a HashMap
is not a Fruit
. You could do the first by providing a constructor that takes a Map<String, String>
argument.
public Fruit(Map<String, String> map) {
this.name = map.get("name");
this.color = map.get("color");
}
It seems like you can use reflection for this
Fruit f = new Fruit();
Class aClass = f.getClass();
for(Field field : aClass.getFields()){
if(map.containsKey(field.getName())){
field.set(f,map.get(field.getName()));
}
}