I have a class, lets call it Fruit, and I have a HashMap. I want to be able to initialize a new instance of Fruit, but set to the values in HashMap. So for example:
Map<String, String> map = new HashMap<String, String>();
map.put("name", "Banana");
map.put("color", "Yellow");
Then I want to be initialize a new Fruit instance like so:
Fruit myFruit = new Fruit(map);
or
Fruit myFruit = (Fruit)map;
Is this possible in Java, by means of iterating the Map?
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()));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With