Java method to assign object field values with Reflection

后端 未结 3 1585
不知归路
不知归路 2021-01-05 02:37

I was wondering whether it would be possible to have something like the following in Java:

public class MyClass {
    private String name;
    private Intege         


        
3条回答
  •  Happy的楠姐
    2021-01-05 03:09

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

提交回复
热议问题