簡體   English   中英

如何映射getter setter類的對象?

[英]How to map objects of getter setter class?

我正在使用GSON在getter setter類中映射JSON。 這是工作。 但是,要實現功能,我必須使用相同的變量但使用不同的類名來創建單獨的Getter Setter類。

public class ABC{

    private int totalUsers;

    public int getTotalUsers() {
        return totalUsers;
    }
    public void setTotalUsers(int totalUsers) {
        this.totalUsers = totalUsers;
    }
}

第二類:

public class DEF{

    private int totalUsers;

    public int getTotalUsers() {
        return totalUsers;
    }
    public void setTotalUsers(int totalUsers) {
        this.totalUsers = totalUsers;
    }
}

現在所需的功能迫使我將值保存在第一類的第二類中。 為此,我必須做:-

def.setTotalUsers(abc.getTotalUsers); // def and abc are objects of their classes

相似地,如果有很多變量,我也必須為它們做同樣的事情,這非常繁瑣。

有什么辦法使我等同於兩個類的對象,並且它們的值會自動復制嗎?

我想,您想使用具有相同值的不同類。 沒有真正的解決方案,但是有可能的方法。

示例: 復制構造函數

public class ABC{
    public ABC(DEF def) {
      // here copy the date form def
    }
}

public class DEF{
    public DEF(ABC abc) {
      // here copy the date form abc
    }
}

使ABC成為DEF的父類將達到目的。 如果適用於您的實現。

如果可以使用第三方庫,請嘗試這些。

通過使用copyProperties(Object,Object)方法從Apache Commons獲得BeanUtils

推土機非常適合進行bean對話。

我認為您應該是可以完成對象屬性復制的工具。

//This sentence should be finish the properties copy,it could copy the source properties
// to the dest properties but you should get an jar 
BeanUtils.copyProperties(java.lang.Object dest,java.lang.Object source);
// You can get the tool of BeanUtils by this Url
http://commons.apache.org/proper/commons-beanutils/

暫無
暫無

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

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