|
| 1 | +package com.blankj.subutil.util; |
| 2 | + |
| 3 | +import java.io.ByteArrayInputStream; |
| 4 | +import java.io.ByteArrayOutputStream; |
| 5 | +import java.io.IOException; |
| 6 | +import java.io.ObjectInputStream; |
| 7 | +import java.io.ObjectOutputStream; |
| 8 | +import java.io.Serializable; |
| 9 | + |
| 10 | +/** |
| 11 | + * <pre> |
| 12 | + * author: Blankj |
| 13 | + * blog : http://blankj.com |
| 14 | + * time : 2018/01/30 |
| 15 | + * desc : 克隆相关工具类 |
| 16 | + * </pre> |
| 17 | + */ |
| 18 | +public final class CloneUtils { |
| 19 | + |
| 20 | + public static <T> T deepClone(final Serializable data) { |
| 21 | + if (data == null) return null; |
| 22 | + return (T) bytes2Object(serializable2Bytes((Serializable) data)); |
| 23 | + } |
| 24 | + |
| 25 | + private static byte[] serializable2Bytes(final Serializable serializable) { |
| 26 | + if (serializable == null) return null; |
| 27 | + ByteArrayOutputStream baos; |
| 28 | + ObjectOutputStream oos = null; |
| 29 | + try { |
| 30 | + oos = new ObjectOutputStream(baos = new ByteArrayOutputStream()); |
| 31 | + oos.writeObject(serializable); |
| 32 | + return baos.toByteArray(); |
| 33 | + } catch (Exception e) { |
| 34 | + e.printStackTrace(); |
| 35 | + return null; |
| 36 | + } finally { |
| 37 | + try { |
| 38 | + if (oos != null) { |
| 39 | + oos.close(); |
| 40 | + } |
| 41 | + } catch (IOException e) { |
| 42 | + e.printStackTrace(); |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + private static Object bytes2Object(final byte[] bytes) { |
| 48 | + if (bytes == null) return null; |
| 49 | + ObjectInputStream ois = null; |
| 50 | + try { |
| 51 | + ois = new ObjectInputStream(new ByteArrayInputStream(bytes)); |
| 52 | + return ois.readObject(); |
| 53 | + } catch (Exception e) { |
| 54 | + e.printStackTrace(); |
| 55 | + return null; |
| 56 | + } finally { |
| 57 | + try { |
| 58 | + if (ois != null) { |
| 59 | + ois.close(); |
| 60 | + } |
| 61 | + } catch (IOException e) { |
| 62 | + e.printStackTrace(); |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | +} |
0 commit comments