java 使用反射分配对象字段值的Java方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7510467/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java method to assign object field values with Reflection
提问by gpol
I was wondering whether it would be possible to have something like the following in 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
}
}
I am really stuck in the setField method and any idea would be very helpful.
我真的被 setField 方法困住了,任何想法都会非常有帮助。
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;
}
采纳答案by Chris Jester-Young
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.
但是由于set
使用错误类型的值调用IllegalArgumentException
无论如何都会生成一个,所以这种检查不是很有用。
回答by P?l Brattberg
回答by adatapost
I'd like to suggest a map
instead of List<T>
.
我想建议一个map
而不是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;