I’m building a FIX message which in typical case would be built something like this:
Message message = new News();
message.setField(new SenderCompID("me"));
message.setField(new TargetCompID("you"));
...
message.setField(new BookSubType("whatever"));
Input is a hash-map:
HashMap<String, String> hmap = new HashMap<String, String>();
hmap.put("SenderCompID", "me");
hmap.put("TargetCompID", "you");
…
hmap.put("BookSubType", "whatever");
One way to construct the message from this input would be:
String senderCompID = hmap.get("SenderCompID");
if (senderCompID != null && !senderCompID.equals("")) {
message.setField(new SenderCompID(senderCompID));
}
…
And so on for every field. But there are too many fields, I will end up spending days writing this. It would be handy if I could dynamically create objects, using hmap keys. My best attempt so far is this:
for (Map.Entry<String, String> entry : hmap.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
Class c = Class.forName(key);
Constructor con = c.getConstructor(SenderCompID.getClass());
Object xyz = con.newInstance(value);
if (xyz instanceof SenderCompID) {
message.setField((SenderCompID) xyz);
} else if ( xyz instanceof TargetCompID ) {
message.setField((TargetCompID) xyz);
} else if …
}
Is there a way to get rid of “if else” statements? The class to which I’m casting to is stored in a String (key), can’t I somehow cast it using the key from the map?