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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 20:17:48  来源:igfitidea点击:

Java method to assign object field values with Reflection

javareflection

提问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 setwith a value of the wrong type will generate an IllegalArgumentExceptionanyway, that sort of check isn't very useful.

但是由于set使用错误类型的值调用IllegalArgumentException无论如何都会生成一个,所以这种检查不是很有用。

回答by P?l Brattberg

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:

虽然我不知道你为什么要这样做(因为你已经有了 getter 和 setter),试试这个:

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

For more info, see this.

有关更多信息,请参阅此

回答by adatapost

I'd like to suggest a mapinstead 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;