Java method for assigning field values โ€‹โ€‹to an object using Reflection

I was wondering if it is possible in Java to have something like the following:

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 because 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; } 
+8
java reflection
source share
3 answers

Of course:

 aField.set(this, aValue); 

First do a type check:

 if (!aField.getType().isInstance(aValue)) throw new IllegalArgumentException(); 

but since calling set with a value of the wrong type will throw an IllegalArgumentException in any case, such a check is not very useful.

+7
source share

Although I'm at a loss as to why you would like to do it like this (since you already have getters and setters), try the following:

 Field aField = getClass().getDeclaredField(aFieldName); aField.set(this, aValue); 

For more information see this .

+4
source share

I would suggest 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; 
+3
source share

All Articles