Android Question [SOLVED] Is there an easy way to clone objects

b4x-de

Member
Licensed User
Hi,

I need to make a deep clone of a given object that contains other objects and lists of other objects. Is there an easy way or a standard way to do this in B4A?

The only one I found was to manually implement a clone operation in each class of the involved objects and call them recursively.

Thanks,
Thomas
 

DonManfred

Expert
Licensed User
What do you want to implement exactly? Clone a List? A Map?
 
Upvote 0

b4x-de

Member
Licensed User
Thank you for helping me to put this more clearly.

I have a class with multiple attributes of different datatypes. Some have simple datatypes (String, Int, etc.). Other attributes have a type of another class or a List.
For example a ClassA might look like this:
B4X:
Sub Class_Globals
  Public id As Int
  Public name As String
  Public objB As ClassB
  Public lstObjsC As List
End Sub

When creating objects of this ClassA they will have simple values (id, name) and references to other objects (objB, lstObjsC). The referenced objects also have references to other objects. This results in an object tree with a root object of ClassA.

I need to make a clone of the root object that includes a clone of the whole object tree. Is there a better way to do this than implementing a clone operation in each involved class and call them recursively?

Thanks,
Thomas
 
Upvote 0

Cableguy

Expert
Licensed User
If you only need to "clone" the class A, then you only need to declare and initialize that class...like

Public MyObject1 as ClassA
Public MyObject2 as ClassA
....
MyObject1.initialize
MyObject2.initialize

Obs. This is pseudo code...
You could also turn your ClassA into a Library.
 
Upvote 0

Erel

Administrator
Staff member
Licensed User
There is a simple way however there are some restrictions. All the types must be supported by B4XSerializator.

B4X:
Sub Clone(o As Object) As Object
   Dim ser As B4XSerializator
   Return ser.ConvertBytesToObject(ser.ConvertObjectToBytes(o))
End Sub


The following types are supported: Lists, Arrays of bytes and Arrays of objects, Maps, Strings, primitive types and user defined types.
This includes all combinations of these types.
 
Last edited:
Upvote 0

mmanso

Active Member
Licensed User
Hi Erel,

I was trying to use your example but I beliave there's a typo on it... shouldn't it be:

B4X:
Sub Clone(o As Object) As Object
    Dim ser As B4XSerializator
    Return ser.ConvertBytesToObject(ser.ConvertObjectToBytes(o))
End Sub

?

ConvertObjectToBytes first, ConvertBytesToObject after.
 
Upvote 0
Top