使用Reflection分配对象字段值的Java方法 [英] Java method to assign object field values with Reflection
本文介绍了使用Reflection分配对象字段值的Java方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道是否有可能在Java中使用以下内容:
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
}
}
我真的陷入了setField方法,任何想法都会非常有用。
I am really stuck in the setField method and any idea would be very helpful.
谢谢!
编辑:原因是我希望在另一个类中有一个方法,如下所示
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;
}
推荐答案
当然:
aField.set(this, aValue);
首先进行类型检查:
if (!aField.getType().isInstance(aValue))
throw new IllegalArgumentException();
但是因为调用设置
的值为错误的类型会生成 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.
这篇关于使用Reflection分配对象字段值的Java方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文