Java のシリアライズ可能なオブジェクトをバイト配列に変換する質問

Java のシリアライズ可能なオブジェクトをバイト配列に変換する質問

シリアル化可能なクラスがあるとしますAppMessage

byte[]それをソケット経由で別のマシンに送信し、受信したバイトから再構築したいと考えています。

どうすればこれを達成できるでしょうか?

ベストアンサー1

送信するバイト配列を準備します。

static byte[] serialize(final Object obj) {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    try (ObjectOutputStream out = new ObjectOutputStream(bos)) {
        out.writeObject(obj);
        out.flush();
        return bos.toByteArray();
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

バイト配列からオブジェクトを作成します。

static Object deserialize(byte[] bytes) {
    ByteArrayInputStream bis = new ByteArrayInputStream(bytes);

    try (ObjectInput in = new ObjectInputStream(bis)) {
        return in.readObject();
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

おすすめ記事