From f6dbb366d8233d6a8340105222494524a8ad7195 Mon Sep 17 00:00:00 2001 From: Suomm <1474983351@qq.com> Date: Sat, 10 Jun 2023 13:52:55 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20Jdk=20Serial=20=E5=B7=A5=E5=85=B7?= =?UTF-8?q?=E7=B1=BB=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/mybatisflex/core/util/SerialUtil.java | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 mybatis-flex-core/src/main/java/com/mybatisflex/core/util/SerialUtil.java diff --git a/mybatis-flex-core/src/main/java/com/mybatisflex/core/util/SerialUtil.java b/mybatis-flex-core/src/main/java/com/mybatisflex/core/util/SerialUtil.java new file mode 100644 index 00000000..52b0f917 --- /dev/null +++ b/mybatis-flex-core/src/main/java/com/mybatisflex/core/util/SerialUtil.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2022-2023, Mybatis-Flex (fuhai999@gmail.com). + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.mybatisflex.core.util; + +import java.io.*; + +/** + * 序列化工具类。 + * + * @author 王帅 + * @since 2023-06-10 + */ +public class SerialUtil { + + public static byte[] writeObject(Object obj) { + try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(bos)) { + oos.writeObject(obj); + oos.flush(); + return bos.toByteArray(); + } catch (IOException e) { + return new byte[0]; + } + } + + public static Object readObject(byte[] bytes) { + try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes); + ObjectInputStream ois = new ObjectInputStream(bis)) { + return ois.readObject(); + } catch (IOException | ClassNotFoundException e) { + return null; + } + } + + public static T cloneObject(Object obj) { + //noinspection unchecked + return (T) readObject(writeObject(obj)); + } + +} \ No newline at end of file