I have a HashMap which has about 500 key-value pairs in it. These values are to be set into attributes of an object, an example of the said object is below-
public class SomeClass {
private String attrib1;
private double attrib2 = Double.NaN
//getters and setters
}
I have to pull the values from the HashMap based on a constant and then set them into this object. Right now, this is how I am doing it
public void someMethod(HashMap<String, String> mapToUse, SomeClass some) {
some.setAttrib1(mapToUse.get(MyConstant.SOME_CONST));
some.setAttrib2(methodToParseDouble(mapToUse.get(MyConstant.SOME_CONST2)));
}
This code works fine without issues, but in my case, I have 500 key-value pairs in the Map and the object contains about 280 attributes. So having 280 hard-coded setters appears ugly in code. Is there a better elegant way to do this?
Right now my code has 280 setter methods called and for each of those I have 280 keys (defined as constants) which I am using to look up the attributes.
I read about BeanUtils, but I am struggling to get it to work with a HashMap. If any of you has a sample code which I can use to pull and set from HashMap, that'd be great.
Edit:
So I got BeanUtils to work, but now I have another problem. BeanUtils working code
testMap.put("attrib1", "2");
testMap.put("attrib2", "3");
testMap.put("completelyDiffAttrib1", "10000"); //This breaks the code
SomeClass testBean = new SomeClass();
BeanUtils.populate(testBean, testMap);
The code above works when I have all the attributes mentioned in the Map in my Object, but if I have extra value in HashMap, which is not present as an attribute in the class then my code breaks. I get a NoClassDef found error-
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/collections/FastHashMap
Caused by: java.lang.ClassNotFoundException: org.apache.commons.collections.FastHashMap
I have added the commons-collections4-4.3.jar to the classpath, which was mentioned elsewhere.
I can think of one approach where I can just filter the Map out first and then run it through populate, but I am looking for better ways to do it.
I cannot change how the source is, i.e., it is going to be a HashMap and I need it in that exact form of the object. I am out of ideas, if anyone has any suggestions, I can do a bit of reading. Thanks!