簡體   English   中英

In Java, how to compare two object and return Map or Xml, Json of properties which is the difference between two object?

[英]In Java, how to compare two object and return Map or Xml, Json of properties which is the difference between two object?

In Java, how to compare two object and return Map or Xml, Json of properties which is the difference between two object? 示例:我有 object 1:

public class User {

    public String username = "1";
     public String password = "1";

    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
}

和 object 2:

public class User {

    public String username = "2";
     public String password = "2";

    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
}

當 ObjectUtils.compare(object1,object2); --> return HashMap 包含“用戶名”和“密碼”作為密鑰

對我來說聽起來像是一個“對象差異”。 如果您只有一個特定的 class 想要比較,您可以簡單地編寫自己的比較邏輯。 如果您需要對任意類使用更通用的方法,那么有些工具使用反射來進行這種 object 比較。

比較對象到底是什么意思?

  1. 要比較 Object 參考,您可以使用a==b
  2. 要比較 Object 值,請使用a.equals(b)
  3. 除此之外,您可以使用Comparable & Comparator interface中的 2 種方法,即a.compareTo(b)compare(a,b)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM