All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.alibaba.schedulerx.worker.util.SerializationUtil Maven / Gradle / Ivy

There is a newer version: 1.12.2
Show newest version
package com.alibaba.schedulerx.worker.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * Java自带的序列化机制,对象必须实现Serializable
 *
 * @author xiaomeng.hxm
 */
public class SerializationUtil {

    // 将对象序列化为字节数组
    public static byte[] serialize(Object obj) throws IOException {
        try (ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream();
             ObjectOutputStream objectOutStream = new ObjectOutputStream(byteOutStream)) {
            objectOutStream.writeObject(obj);
            return byteOutStream.toByteArray();
        }
    }
    
    // 将字节数组反序列化为对象
    public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
        try (ByteArrayInputStream byteInStream = new ByteArrayInputStream(bytes);
             ObjectInputStream objectInStream = new ObjectInputStream(byteInStream)) {
            return objectInStream.readObject();
        }
    }
    
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy