回答編集履歴

1

内容修正

2020/05/09 22:14

投稿

shiketa
shiketa

スコア3971

test CHANGED
@@ -48,21 +48,21 @@
48
48
 
49
49
  public Person clone() {
50
50
 
51
- try {
51
+ try (
52
-
52
+
53
- final ByteArrayOutputStream baos = new ByteArrayOutputStream();
53
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
54
-
54
+
55
- final ObjectOutputStream oos = new ObjectOutputStream(baos);
55
+ ObjectOutputStream oos = new ObjectOutputStream(baos);) {
56
56
 
57
57
  oos.writeObject(this);
58
58
 
59
59
  oos.close();
60
60
 
61
-
61
+ try (
62
-
62
+
63
- final ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
63
+ ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
64
-
64
+
65
- try (final ObjectInputStream ois = new ObjectInputStream(bais);) {
65
+ ObjectInputStream ois = new ObjectInputStream(bais);) {
66
66
 
67
67
  return (Person) ois.readObject();
68
68
 
@@ -189,3 +189,75 @@
189
189
  p2Person [name =name1, age=21, item=Item [name =アイテム1]]
190
190
 
191
191
  ```
192
+
193
+
194
+
195
+ ----
196
+
197
+
198
+
199
+ 外に切り出して、こんなの用意しとくのもよろしいかと。
200
+
201
+
202
+
203
+ ```java
204
+
205
+ import java.io.*;
206
+
207
+
208
+
209
+ public class Clones {
210
+
211
+ public static <A extends Serializable> A clone(final A source) {
212
+
213
+ if(source == null) return source;
214
+
215
+
216
+
217
+ try (
218
+
219
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
220
+
221
+ ObjectOutputStream oos = new ObjectOutputStream(baos);) {
222
+
223
+ oos.writeObject(source);
224
+
225
+ oos.close();
226
+
227
+ try (
228
+
229
+ ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
230
+
231
+ ObjectInputStream ois = new ObjectInputStream(bais);) {
232
+
233
+ return (A) ois.readObject();
234
+
235
+ }
236
+
237
+ } catch (Exception e) {
238
+
239
+ throw new RuntimeException(e);
240
+
241
+ }
242
+
243
+ }
244
+
245
+ }
246
+
247
+ ```
248
+
249
+
250
+
251
+ ```java
252
+
253
+ @Test
254
+
255
+ public void hoge2() throws Exception {
256
+
257
+ Item item = new Item("アイテム1");
258
+
259
+ Person p1 = new Person("name1", 21, item);
260
+
261
+ Person p2 = Clones.clone(p1);
262
+
263
+ ```