gpol gpol - 1 year ago 55
Java Question

Java method to assign object field values with Reflection

I was wondering whether it would be possible to have something like the following in Java:

public class MyClass {
private String name;
private Integer age;
private Date dateOfBirth;
// constructors, getters, setters

public void setField(String aFieldName, Object aValue) {
Field aField = getClass().getDeclaredField(aFieldName);
// use: aField.set(...) with proper type handling

I am really stuck in the setField method and any idea would be very helpful.


EDIT: The reason for this is that I would like to have a method in another class like the following

public static MyClass setAll(List<String> fieldNames, List<Object> fieldValues) {
MyClass anObject = new MyClass();
// iterate fieldNames and fieldValues and set for each fieldName
// the corresponding field value
return anObject;

Answer Source


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download