Java:如何根据给定的值映射更新一些POJO字段?

huangapple go评论78阅读模式
英文:

Java: How to update some of POJO fields according to a given map of values?

问题

以下是翻译好的内容:

我需要根据仅包含更改的映射来更新几个POJO字段。

例如(松散编码):

类MyClass{

   public MyClass(a,b,c);

   private int a;
   private int b;
   private int c;
}

int main(){
  Map<String, String> keyValueMap = new HashMap<>();
  
  MyClass obj = new MyClass(1,2,3);
  keyValueMap.put("c", 6);
  keyValueMap.put("b", 4);

  // 仅更新obj的b和c值:
  updateObj(obj, keyValueMap);

  keyValueMap.put("a", 5);
  keyValueMap.put("b", 7);

  // 仅更新obj的a和b值:
  updateObj(obj, keyValueMap);
}

void updateObj(MyClass obj, Map<String, String> keyValueMap){

 for (Map.Entry<String,String> entry : keyValueMap.entrySet())  
      if(entry.getKey().equals("a")
        obj.setA(entry.getValue());
      if(entry.getKey().equals("b")
        obj.setB(entry.getValue());
      if(entry.getKey().equals("c")
        obj.setC(entry.getValue());
  }
}

除了完整的if链外,是否有更好的方法来实现updateObj()吗?

谢谢大家。

英文:

I need to update several POJO fields according to a map which holds only the changes.

For example (loosely coded) :

Class MyClass{

   public MyClass(a,b,c);

   private int a;
   private int b;
   private int c;
}

int main(){
  Map&lt;String, String&gt; keyValueMap = new HashMap&lt;&gt;();
  
  MyClass obj = new MyClass(1,2,3);
  keyValueMap.put(&quot;c&quot;, 6);
  keyValueMap.put(&quot;b&quot;, 4);

  //Update only b and c values of obj:
  updateObj(obj, keyValueMap);

  keyValueMap.put(&quot;a&quot;, 5);
  keyValueMap.put(&quot;b&quot;, 7);

  //Update only a and b values of obj:
  updateObj(obj, keyValueMap);
}

void updateObj(MyClass obj, Map&lt;String, String&gt; keyValueMap){

 for (Map.Entry&lt;String,String&gt; entry : keyValueMap.entrySet())  
      if(entry.getKey().equals(&quot;a&quot;)
        obj.setA(entry.getValue();
      if(entry.getKey().equals(&quot;b&quot;)
        obj.setB(entry.getValue();
      if(entry.getKey().equals(&quot;c&quot;)
        obj.setC(entry.getValue();
  }
}

Is there a better method to implement updateObj() apart of a complete if's chain?

Thank you all.

答案1

得分: 1

示例代码更新方法):

    static void updateObj(MyClass obj, Map<String, Integer> keyValueMap) {
            try {
                Field declaredField =  null;
                for(String key : keyValueMap.keySet()) {
                    declaredField = MyClass.class.getDeclaredField(key);
                    boolean accessible = declaredField.isAccessible();
                    declaredField.setAccessible(true);
                    declaredField.set(obj, keyValueMap.get(key));
                    declaredField.setAccessible(accessible);
                }
            } catch (NoSuchFieldException | IllegalAccessException e) {
                e.printStackTrace();
            }
    
        }
英文:

Example code (update method):

static void updateObj(MyClass obj, Map&lt;String, Integer&gt; keyValueMap) {
        try {
            Field declaredField =  null;
            for(String key:keyValueMap.keySet()) {
                declaredField = MyClass.class.getDeclaredField(key);
                boolean accessible = declaredField.isAccessible();
                declaredField.setAccessible(true);
                declaredField.set(obj, keyValueMap.get(key));
                declaredField.setAccessible(accessible);
            }
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }

    }

答案2

得分: 1

你可以使用Java的反射机制来实现你想要做的操作:

static void updateObj(Main obj, Map<String, Integer> keyValueMap){
    try {
        for (Map.Entry<String, Integer> entry : keyValueMap.entrySet()) {
            Field field = Main.class.getField(entry.getKey());
            field.setAccessible(true);
            field.set(obj, entry.getValue());
        }
    } catch (Exception e) {}
}
英文:

You can use Java reflection to do what you want to do:

static void updateObj(Main obj, Map&lt;String, Integer&gt; keyValueMap){
    try {
        for (Map.Entry&lt;String,Integer&gt; entry : keyValueMap.entrySet()) {
            Field field = Main.class.getField(entry.getKey());
            field.setAccessible(true)
            field.set(obj,entry.getValue());
        }
    } catch(Exception e) {}
}

答案3

得分: 0

你可以简单地使用反射API。以下是基于你的代码的示例:

public class Main1 {
    public static void main(String[] args) {
        Map<String, String> keyValueMap = new HashMap<>();

        MyClass obj = new MyClass(1, 2, 3);
        keyValueMap.put("c", "6");
        keyValueMap.put("b", "4");

        System.out.println(obj);

        // 仅更新 obj 的 b 和 c 值:
        updateObj(obj, keyValueMap);

        System.out.println(obj);

        keyValueMap.put("a", "5");
        keyValueMap.put("b", "7");

        // 仅更新 obj 的 a 和 b 值:
        updateObj(obj, keyValueMap);

        System.out.println(obj);
    }

    private static void updateObj(MyClass myClass, Map<String, String> map) {
        Class<MyClass> clazz = MyClass.class;
        for (String fieldName : map.keySet()) {
            try {
                Field field = clazz.getDeclaredField(fieldName);
                field.setAccessible(true);
                field.set(myClass, Integer.parseInt(map.get(fieldName)));
            } catch (NoSuchFieldException ex) {
                System.out.println("找不到该字段!!!");
            } catch (IllegalAccessException ex) {
                System.out.println(ex);
            }
        }
    }
}

class MyClass {
    private int a;
    private int b;
    private int c;

    public MyClass(int a, int b, int c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    @Override
    public String toString() {
        return "MyClass{" + "a=" + a + ", b=" + b + ", c=" + c + '}';
    }
}

注意:不要忘记为私有成员使用 field.setAccessible(true);,否则会出现 IllegalAccessException。

英文:

You can simply use Reflection API.
Here is an example based on your code:

public class Main1 {
public static void main(String[] args) {
Map&lt;String, String&gt; keyValueMap = new HashMap&lt;&gt;();
MyClass obj = new MyClass(1,2,3);
keyValueMap.put(&quot;c&quot;, &quot;6&quot;);
keyValueMap.put(&quot;b&quot;, &quot;4&quot;);
System.out.println(obj);
//Update only b and c values of obj:
updateObj(obj, keyValueMap);
System.out.println(obj);
keyValueMap.put(&quot;a&quot;, &quot;5&quot;);
keyValueMap.put(&quot;b&quot;, &quot;7&quot;);
//Update only a and b values of obj:
updateObj(obj, keyValueMap);
System.out.println(obj);
}
private static void updateObj(MyClass myClass, Map&lt;String, String&gt; map) {
Class&lt;MyClass&gt; clazz = MyClass.class;
for (String fieldName: map.keySet()) {
try {
Field field = clazz.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(myClass, Integer.parseInt(map.get(fieldName)));
} catch (NoSuchFieldException ex) {
System.out.println(&quot;No Such Field Found!!!&quot;);
} catch (IllegalAccessException ex) {
System.out.println(ex);
}
}
}
}
class MyClass {
private int a;
private int b;
private int c;
public MyClass(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
@Override
public String toString() {
return &quot;MyClass{&quot; + &quot;a=&quot; + a + &quot;, b=&quot; + b + &quot;, c=&quot; + c + &#39;}&#39;;
}
}

Note: Do not forget to use field.setAccessible(true); for private members; Otherwise you will get an IllegalAccessException.

huangapple
  • 本文由 发表于 2020年5月5日 14:53:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/61607358.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定