简体   繁体   中英

How to map objects of getter setter class?

I am using GSON to map JSON in getter setter classes. It is working. However, to achieve a functionality, i have to create separate Getter Setter Classes with the same variable but different class name.

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

Dozer is good for bean conversations.

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM