简体   繁体   English

如何映射getter setter类的对象?

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

I am using GSON to map JSON in getter setter classes. 我正在使用GSON在getter setter类中映射JSON。 It is working. 这是工作。 However, to achieve a functionality, i have to create separate Getter Setter Classes with the same variable but different class name. 但是,要实现功能,我必须使用相同的变量但使用不同的类名来创建单独的Getter Setter类。

public class ABC{

    private int totalUsers;

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

Second Class :- 第二类:

public class DEF{

    private int totalUsers;

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

Now the functionality required force me to save values in the second class from the first class. 现在所需的功能迫使我将值保存在第一类的第二类中。 For that i have to do :- 为此,我必须做:-

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

Similary, if there are many variable i have to do the same for them also which is very tedious. 相似地,如果有很多变量,我也必须为它们做同样的事情,这非常繁琐。

Is there any way that somehow i equate the objects of the two classes and their values get copied automatically ? 有什么办法使我等同于两个类的对象,并且它们的值会自动复制吗?

I think, you would like to use different classes with the same value. 我想,您想使用具有相同值的不同类。 There is no true solution but there are possible ways. 没有真正的解决方案,但是有可能的方法。

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

Making ABC the parent class of DEF will do the trick. 使ABC成为DEF的父类将达到目的。 If it works for your implementation. 如果适用于您的实现。

If it is okay to use third party libraries, Then try these.. 如果可以使用第三方库,请尝试这些。

BeanUtils from Apache Commons by using copyProperties(Object, Object) method. 通过使用copyProperties(Object,Object)方法从Apache Commons获得BeanUtils

Dozer is good for bean conversations. 推土机非常适合进行bean对话。

I think you should be a tool which can finish the object property copy.the code like this. 我认为您应该是可以完成对象属性复制的工具。

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