MCPcopy Create free account
hub / github.com/badvision/jace / copyObject

Method copyObject

src/main/java/jace/state/StateValue.java:58–93  ·  view source on GitHub ↗
(T currentValue)

Source from the content-addressed store, hash-verified

56 }
57
58 @SuppressWarnings("all")
59 private T copyObject(T currentValue) {
60 if (currentValue == null) return null;
61 if (type.isPrimitive()) {
62 return currentValue;
63 }
64 if (!type.isArray()) {
65 try {
66 return (T) type.getMethod("clone").invoke(currentValue);
67 } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
68 try {
69 // Use serialization to build a deep copy
70 ByteArrayOutputStream baos = new ByteArrayOutputStream();
71 ObjectOutputStream oos = new ObjectOutputStream(baos);
72 oos.writeObject(currentValue);
73
74 ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
75 ObjectInputStream ois = new ObjectInputStream(bais);
76 return (T) ois.readObject();
77 } catch (IOException | ClassNotFoundException e) {
78 return null;
79 }
80 }
81 } else if (type.isArray()) {
82 // Cross fingers! I hope this works and I don't have to investigate primite types further...
83 if (currentValue instanceof byte[]) {
84 byte[] array = (byte[]) currentValue;
85 return (T) Arrays.copyOf(array, array.length);
86 } else {
87 Object[] array = (Object[]) currentValue;
88 return (T) Arrays.copyOf(array, array.length);
89 }
90 }
91
92 return currentValue;
93 }
94}

Callers 1

StateValueMethod · 0.95

Calls 2

writeObjectMethod · 0.80
readObjectMethod · 0.80

Tested by

no test coverage detected