How do I copy an object in Java?

后端 未结 23 2662
终归单人心
终归单人心 2020-11-21 04:50

Consider the code below:

DummyBean dum = new DummyBean();
dum.setDummy(\"foo\");
System.out.println(dum.getDummy()); // prints \'foo\'

DummyBean dumtwo = du         


        
23条回答
  •  粉色の甜心
    2020-11-21 05:16

    This works too. Assuming model

    class UserAccount{
       public int id;
       public String name;
    }
    

    First add compile 'com.google.code.gson:gson:2.8.1' to your app>gradle & sync. Then

    Gson gson = new Gson();
    updateUser = gson.fromJson(gson.toJson(mUser),UserAccount.class);
    

    You can exclude using a field by using transient keyword after access modifier.

    Note: This is bad practice. Also don't recommend to use Cloneable or JavaSerialization It's slow and broken. Write copy constructor for best performance ref.

    Something like

    class UserAccount{
            public int id;
            public String name;
            //empty constructor
            public UserAccount(){}
            //parameterize constructor
            public UserAccount(int id, String name) {
                this.id = id;
                this.name = name;
            }
    
            //copy constructor
            public UserAccount(UserAccount in){
                this(in.id,in.name);
            }
        }
    

    Test stats of 90000 iteration:
    Line UserAccount clone = gson.fromJson(gson.toJson(aO), UserAccount.class); takes 808ms

    Line UserAccount clone = new UserAccount(aO); takes less than 1ms

    Conclusion: Use gson if your boss is crazy and you prefer speed. Use second copy constructor if you prefer quality.

    You can also use copy constructor code generator plugin in Android Studio.

提交回复
热议问题