tags:

views:

88

answers:

4

I have a Map Object and the data in map is like

col1 -> data1, col2 -> data2, col3 -> data3 ...

Is it possible to convert this Map to Java Object like

class MapObj {

    String col1 = "data1";
    String col2 = "data2";
    String col3 = "data3";

}
A: 

I don't know of any pre-made libs that will do it for you, but it should be quite trivial using the java.lang.reflect API. Specifically, the Field#set* methods. Of course, however, you would need to have a pre-defined class with the fields (keys) defined.

kyl
+4  A: 

Whilst it is possible to create classes at runtime with custom class loaders, it is relatively pointless. How would you access the fields (other than reflection and other dynamically created classes)?

Tom Hawtin - tackline
+1  A: 

Are there a fixed set of named entries in the Map? If so, you can just create the MapObj class as you have it and assign the three fields by saying myMapObj.col1 = myMap.get("col1"); and so on.

But stepping back from this question for a moment, what's the larger problem you're trying to solve? A Map itself is actually a very convenient container for this data already, so perhaps you can just use the Map for the same purpose that you were planning to use MapObj for?

Jim Ferrans
col1, col2,col3,.. are dynamic
Madhu
So you want to create a new class for each *instance* of the Map? What code would then operate on instances of the new classes and for what purposes? Or is this just an intellectual exercise?
Jim Ferrans
+1  A: 

I don't see any point in putting a bunch of Map values to a class. If you want static access, why not try the opposite:

class MapAccess {
  Map<String, String> backingMap = ...

  public String getCol1() {
    return backingMap.get("col1");
  }

  public String getCol2() {
    return backingMap.get("col2");
  }

  public String getCol3() {
    return backingMap.get("col3");
  }
}

This way, you'r application doesn't need to know about the Map and you don't get lost with reflection.

Hardcoded