假设我有一个可序列化的类AppMessage。

我想通过套接字将它作为字节[]传输到另一台机器,在那里它从接收到的字节重建。

我怎么才能做到呢?


当前回答

Spring框架org.springframework.util.SerializationUtils

byte[] data = SerializationUtils.serialize(obj);

其他回答

我也推荐使用SerializationUtils工具。我想对@Abilash的错误评论做一个调整。SerializationUtils.serialize()方法不限制为1024字节,这与这里的另一个答案相反。

public static byte[] serialize(Object object) {
    if (object == null) {
        return null;
    }
    ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
    try {
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(object);
        oos.flush();
    }
    catch (IOException ex) {
        throw new IllegalArgumentException("Failed to serialize object of type: " + object.getClass(), ex);
    }
    return baos.toByteArray();
}

乍一看,您可能认为新的ByteArrayOutputStream(1024)只允许固定的大小。但是如果你仔细观察ByteArrayOutputStream,你会发现流在必要时还会增长:

该类实现了一个输出流,其中数据为 写入字节数组。缓冲区自动作为数据增长 被写入。 可以使用toByteArray()和 toString ()。

可以通过SerializationUtils完成,通过ApacheUtils的serialize & deserialize方法将对象转换为字节[],反之亦然,如@uris answer中所述。

通过序列化将一个对象转换为字节[]:

byte[] data = SerializationUtils.serialize(object);

通过反序列化将byte[]转换为object::

Object object = (Object) SerializationUtils.deserialize(byte[] data)

点击下载org-apache-commons-lang.jar的链接

通过点击整合.jar文件:

FileName ->打开Medule Settings ->选择你的模块-> Dependencies ->添加Jar文件,完成。

希望这能有所帮助。

Java 8+的代码示例:

public class Person implements Serializable {

private String lastName;
private String firstName;

public Person() {
}

public Person(String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getFirstName() {
    return firstName;
}

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

@Override
public String toString() {
    return "firstName: " + firstName + ", lastName: " + lastName;
}
}


public interface PersonMarshaller {
default Person fromStream(InputStream inputStream) {
    try (ObjectInputStream objectInputStream = new ObjectInputStream(inputStream)) {
        Person person= (Person) objectInputStream.readObject();
        return person;
    } catch (IOException | ClassNotFoundException e) {
        System.err.println(e.getMessage());
        return null;
    }
}

default OutputStream toStream(Person person) {
    try (OutputStream outputStream = new ByteArrayOutputStream()) {
        ObjectOutput objectOutput = new ObjectOutputStream(outputStream);
        objectOutput.writeObject(person);
        objectOutput.flush();
        return outputStream;
    } catch (IOException e) {
        System.err.println(e.getMessage());
        return null;
    }

}

}

另一个有趣的方法来自com.fasterxml.jackson.databind.ObjectMapper

byte[] data = new ObjectMapper().writeValueAsBytes(JAVA_OBJECT_HERE)

Maven的依赖

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
</dependency>

如果你想要一个不错的无依赖复制粘贴解决方案。获取下面的代码。

例子

MyObject myObject = ...

byte[] bytes = SerializeUtils.serialize(myObject);
myObject = SerializeUtils.deserialize(bytes);

import java.io.*;

public class SerializeUtils {

    public static byte[] serialize(Serializable value) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        try(ObjectOutputStream outputStream = new ObjectOutputStream(out)) {
            outputStream.writeObject(value);
        }

        return out.toByteArray();
    }

    public static <T extends Serializable> T deserialize(byte[] data) throws IOException, ClassNotFoundException {
        try(ByteArrayInputStream bis = new ByteArrayInputStream(data)) {
            //noinspection unchecked
            return (T) new ObjectInputStream(bis).readObject();
        }
    }
}