Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

63
LINES

< > BotCompany Repo | #1001005 // clone function

JavaX fragment (include)

1  
static Object clone(Object o) {
2  
  return clone(o, new IdentityHashMap);
3  
}
4  
5  
static Object clone(Object o, IdentityHashMap seen) ctex {
6  
  if (o == null)
7  
    return o;
8  
    
9  
  Object y = seen.get(o);
10  
  if (y != null) return y;
11  
  
12  
  if (o instanceof List) {
13  
    print("Cloning list: " + o);
14  
    List l = new ArrayList();
15  
    seen.put(o, l);
16  
    for (Object x : (List) o)
17  
      l.add(clone(x, seen));
18  
    return l;
19  
  }
20  
  
21  
  if (o instanceof Map) {
22  
    Map m = o instanceof TreeMap ? new TreeMap() : new HashMap();
23  
    seen.put(o, m);
24  
    for (O entry : ((Map) o).entrySet()) {
25  
      Map.Entry e = (Map.Entry) entry;
26  
      m.put(clone(e.getKey(), seen), clone(e.getValue(), seen));
27  
    }
28  
    return m;
29  
  }
30  
  
31  
  if (o instanceof String || o instanceof Number || o instanceof Boolean)
32  
    return o;
33  
    
34  
  if (o instanceof Object[]) {
35  
    Object[] l = (Object[]) o;
36  
    Object[] l2 = l.clone();
37  
    seen.put(o, l2);
38  
    for (int i = 0; i < l.length; i++)
39  
      l2[i] = clone(l[i], seen);
40  
    return l2;
41  
  }
42  
  
43  
  // clone an arbitrary custom object
44  
45  
  // TODO: use Constructor object and setAccessible
46  
  print("Cloning custom: " + o);
47  
  Object clone = o.getClass().newInstance();
48  
  seen.put(o, clone);
49  
  Class c = o.getClass();
50  
  while (c != Object.class) {
51  
    Field[] fields = c.getDeclaredFields();
52  
    for (Field field : fields) {
53  
      if ((field.getModifiers() & Modifier.STATIC) != 0)
54  
        continue;
55  
      Object value;
56  
      field.setAccessible(true);
57  
      value = field.get(o);
58  
      field.set(clone, clone(value, seen));
59  
    }
60  
    c = c.getSuperclass();
61  
  }
62  
  return clone;
63  
}

download  show line numbers  debug dex  old transpilations   

Travelled to 13 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #1001005
Snippet name: clone function
Eternal ID of this version: #1001005/1
Text MD5: 0ad48c6a4427a8b5f8ed26fe9f23be70
Author: stefan
Category:
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2015-09-16 17:44:47
Source code size: 1643 bytes / 63 lines
Pitched / IR pitched: No / Yes
Views / Downloads: 524 / 517
Referenced in: [show references]