Using Parcel to clone an object?

后端 未结 3 1244
猫巷女王i
猫巷女王i 2021-02-06 10:09

I have a class which has implemented Parcelable. Can I do something like the following to create a new instance of a class?:

Foo foo = new Foo(\"a\", \"b\", \"c\         


        
相关标签:
3条回答
  • 2021-02-06 10:24

    Yes, assuming that your parcel implementation correctly writes and reads all of the variables in Foo, that should create a clone.

    0 讨论(0)
  • 2021-02-06 10:31

    There is a shorter way:

    Foo foo1 = new Foo("a", "b", "c");
    Parcel p = Parcel.obtain();
    p.writeValue(foo1);
    p.setDataPosition(0);
    Foo foo2 = (Foo)p.readValue(Foo.class.getClassLoader());
    p.recycle();
    
    0 讨论(0)
  • 2021-02-06 10:40

    I had the same problem and here is my solution:

    Parcel p = Parcel.obtain();
    foo.writeToParcel(p, 0);
    p.setDataPosition(0); // <-- this is the key
    Foo foo2 = Foo.CREATOR.createFromParcel(p);
    p.recycle();
    
    0 讨论(0)
提交回复
热议问题