I have a long switch statement that I'm trying to make more efficient. It parses an xml feed and populates a Java object using the xml values. There are maybe 30 fields so it's kind of tedious to write a switch case for each field.
switch (currentTagName) {
case "longitude" :
observation.setLongitude(Double.parseDouble(parser.getText()));
break;
case "elevation" :
observation.setElevation(Integer.parseInt(parser.getText()));
break;
case "observation_time" :
observation.setObservation_time(parser.getText());
break;
You can see, the only difference in how each case is handled is due to the type of data I'm working with.
I'm trying to figure out the syntax for doing something similar to this (pseudocode):
//get the data type of this variable, somehow or other
String inputType = Observation.getMethodInputType("set" + currentTagName);
//switch on that data type
switch(inputType) {
case "Integer":
observation.set{currentTagName}(Integer.parseInt(parser.getText()));
break;
case "Double":
observation.set{currentTagName}(Double.parseDouble(parser.getText()));
break;
case "String":
observation.set{currentTagName}(parser.getText());
break;
}
It's just that my Java syntax is pretty rusty, I'm not sure what the correct way is to do this (or if you even can), especially for the set{currentTagName} part and getMethodInputType() (is that a thing?).
What's the correct way to do this?