|
12 | 12 | */
|
13 | 13 | public class SerializableCloner implements Cloner {
|
14 | 14 |
|
15 |
| - @Override |
16 |
| - public boolean canClone(Object source) { |
17 |
| - if (source == null) |
18 |
| - return false; |
19 |
| - return source instanceof Serializable; |
20 |
| - } |
| 15 | + @Override |
| 16 | + public boolean canClone(Object source) { |
| 17 | + if (source == null) |
| 18 | + return false; |
| 19 | + return source instanceof Serializable; |
| 20 | + } |
21 | 21 |
|
22 |
| - @Override |
23 |
| - public Object clone(Object source) { |
24 |
| - return SerializableCloner.clone((Serializable)source); |
25 |
| - } |
| 22 | + @Override |
| 23 | + public Object clone(Object source) { |
| 24 | + return SerializableCloner.clone((Serializable) source); |
| 25 | + } |
26 | 26 |
|
27 |
| - /** |
28 |
| - * Clone the given object using serialization. |
29 |
| - * @param obj - the object to clone. |
30 |
| - * @return The cloned object. |
31 |
| - * @throws RuntimeException If we were unable to clone the object. |
32 |
| - */ |
33 |
| - @SuppressWarnings("unchecked") |
34 |
| - public static <T extends Serializable> T clone(final T obj) { |
35 |
| - try { |
36 |
| - ByteArrayOutputStream out = new ByteArrayOutputStream(); |
37 |
| - ObjectOutputStream oout = new ObjectOutputStream(out); |
| 27 | + /** |
| 28 | + * Clone the given object using serialization. |
| 29 | + * @param obj - the object to clone. |
| 30 | + * @return The cloned object. |
| 31 | + * @throws RuntimeException If we were unable to clone the object. |
| 32 | + */ |
| 33 | + @SuppressWarnings("unchecked") |
| 34 | + public static <T extends Serializable> T clone(final T obj) { |
| 35 | + try { |
| 36 | + if (obj instanceof Serializable) { |
| 37 | + ByteArrayOutputStream out = new ByteArrayOutputStream(); |
| 38 | + ObjectOutputStream oout = new ObjectOutputStream(out); |
38 | 39 |
|
39 |
| - oout.writeObject(obj); |
40 |
| - ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(out.toByteArray())); |
41 |
| - return (T) in.readObject(); |
42 |
| - |
43 |
| - } catch (Exception e) { |
44 |
| - throw new RuntimeException("Unable to clone object " + obj, e); |
45 |
| - } |
46 |
| - } |
| 40 | + oout.writeObject(obj); |
| 41 | + ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(out.toByteArray())); |
| 42 | + return (T) in.readObject(); |
| 43 | + } else { |
| 44 | + throw new RuntimeException("Object " + obj + " is not serializable!"); |
| 45 | + } |
| 46 | + } catch (Exception e) { |
| 47 | + throw new RuntimeException("Unable to clone object " + obj + " (" + obj.getClass().getName() + ")", e); |
| 48 | + } |
| 49 | + } |
47 | 50 | }
|
0 commit comments