【问题标题】:How to map objects of getter setter class?如何映射getter setter类的对象?
【发布时间】:2014-01-15 04:48:21
【问题描述】:

我正在使用 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

类似,如果有很多变量,我也必须为它们做同样的事情,这也很乏味。

有什么方法可以让我以某种方式将两个类的对象等同起来,并且它们的值会被自动复制?

【问题讨论】:

  • ABC JSON DEF?

标签: java android


【解决方案1】:

我认为,您希望使用具有相同值的不同类。没有真正的解决方案,但有可能的方法。

示例:Copy constructors

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
    }
}

【讨论】:

    【解决方案2】:

    ABC 设为DEF 的父类就可以了。如果它适用于您的实施。

    【讨论】:

      【解决方案3】:

      如果可以使用第三方库,那就试试这些吧..

      BeanUtils 来自 Apache Commons,使用 copyProperties(Object, Object) 方法。

      Dozer 适合 bean 对话。

      【讨论】:

        【解决方案4】:

        我觉得你应该是一个可以完成对象属性复制的工具。代码是这样的。

        //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/
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-09-10
          • 2013-04-09
          相关资源
          最近更新 更多