8

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.

Thanks!

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;
}

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes I tried this but the thing is I would like to add some kind of type checking and appropriate casting in the method. Any ideas?
You can do type checking if you want (but if all you do with a failed check is to throw, then that's pointless, since the reflection mechanism will throw for you). No casting will be appropriate.
4

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.

2 Comments

Silly of me. I edited my question in order to explain why I want it.
OK, is the answer good enough then? If you want to, you also have more specialized versions of set, such as setLong, setFloat, setBoolean etc. See the Javadoc referenced.
3

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.