Let's say I have simple HashMap
:
Map<String, String> map = new HashMap<>();
map.put("field1","value1");
map.put("field2", "value2");
I also have simple java class:
class SimpleClass {
public String field1;
public String field2;
}
What is simplest and most elegant way to create SimpleClass
instance with corresponding fields/values taken from map? In this case, resulting SimpleClass
instance should get field1
value 'value1and
field2value
value2`.
SimpleClass
is already defined, now we need to find matching keys in map, if match found, it's value should be assigned to corresponding class field.
In my real application, I will get list of maps and I need to transform it into List<SimpleClass>
. Map can contain additional keys, that need to be ommited (if no matching class field is available).
Can I use (for example) Guava to make transoformation like this? I'm on Android so java streams can't be used so far.
[edit]
My attempt:
private SimpleClass mapToObject(Map<String, String> map)
{
SimpleClass result = new SimpleClass();
for(Field f: result.getClass().getDeclaredFields())
{
try
{
f.setAccessible(true);
f.set(result,map.get(f.getName()));
}
catch (Exception e)
{
Log.d("error", e.toString());
}
}
return result;
}