使用Reflection分配对象字段值的Java方法

我想知道是否有可能在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 } } 

我真的陷入了setField方法,任何想法都会非常有用。

谢谢!

编辑:这是因为我希望在另一个类中有一个方法,如下所示

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

当然:

 aField.set(this, aValue); 

要先进行类型检查:

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

但是,因为使用错误类型的值调用set无论如何都会生成IllegalArgumentException ,这种检查不是很有用。

虽然我不知道为什么你会这样做(因为你已经有吸气剂和制定者),试试这个:

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

有关详细信息, 请参阅此内容 。

我想建议一张map而不是List

  for(Map.Entry entry:map.entrySet()) { Field aField = anObject.getClass().getDeclaredField(entry.getKey()); if(entry.getValue().getClass().equals(aField.getType())) aField.set(anObject,entry.getValue()); } return anObject;