Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I cast a HashMap to a concrete class?

Tags:

java

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?

like image 495
josef.van.niekerk Avatar asked Jul 26 '11 19:07

josef.van.niekerk


2 Answers

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");
}
like image 147
ColinD Avatar answered Oct 02 '22 19:10

ColinD


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()));
  }
}
like image 35
Anni Avatar answered Oct 02 '22 21:10

Anni