I was wondering whether it would be possible to have something like the following in Java:
public class MyClass {
private String name;
private Intege
I'd like to suggest a map
instead of List<T>
.
for(Map.Entry<String,Object> entry:map.entrySet())
{
Field aField = anObject.getClass().getDeclaredField(entry.getKey());
if(entry.getValue().getClass().equals(aField.getType()))
aField.set(anObject,entry.getValue());
}
return anObject;
Sure:
aField.set(this, aValue);
To do type checking first:
if (!aField.getType().isInstance(aValue))
throw new IllegalArgumentException();
but since calling set
with a value of the wrong type will generate an IllegalArgumentException
anyway, that sort of check isn't very useful.
Though I'm at a loss as to why you would want to do it like that (since you already have getters and setters), try this:
Field aField = getClass().getDeclaredField(aFieldName);
aField.set(this, aValue);
For more info, see this.