static Object clone(Object o) {
return clone(o, new IdentityHashMap);
}
static Object clone(Object o, IdentityHashMap seen) ctex {
if (o == null)
return o;
Object y = seen.get(o);
if (y != null) return y;
if (o instanceof List) {
print("Cloning list: " + o);
List l = new ArrayList();
seen.put(o, l);
for (Object x : (List) o)
l.add(clone(x, seen));
return l;
}
if (o instanceof Map) {
Map m = o instanceof TreeMap ? new TreeMap() : new HashMap();
seen.put(o, m);
for (O entry : ((Map) o).entrySet()) {
Map.Entry e = (Map.Entry) entry;
m.put(clone(e.getKey(), seen), clone(e.getValue(), seen));
}
return m;
}
if (o instanceof String || o instanceof Number || o instanceof Boolean)
return o;
if (o instanceof Object[]) {
Object[] l = (Object[]) o;
Object[] l2 = l.clone();
seen.put(o, l2);
for (int i = 0; i < l.length; i++)
l2[i] = clone(l[i], seen);
return l2;
}
// clone an arbitrary custom object
// TODO: use Constructor object and setAccessible
print("Cloning custom: " + o);
Object clone = o.getClass().newInstance();
seen.put(o, clone);
Class c = o.getClass();
while (c != Object.class) {
Field[] fields = c.getDeclaredFields();
for (Field field : fields) {
if ((field.getModifiers() & Modifier.STATIC) != 0)
continue;
Object value;
field.setAccessible(true);
value = field.get(o);
field.set(clone, clone(value, seen));
}
c = c.getSuperclass();
}
return clone;
}
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: | 1081 / 1029 |
| Referenced in: | [show references] |