在java中将任何对象转换为字节数组 [英] Converting any object to a byte array in java

查看:40
本文介绍了在java中将任何对象转换为字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 X 类型的对象,我想在将它发送到 S3 之前将其转换为字节数组.谁能告诉我如何做到这一点?感谢您的帮助.

I have an object of type X which I want to convert into byte array before sending it to store in S3. Can anybody tell me how to do this? I appreciate your help.

推荐答案

你要做的就是所谓的序列化".有几种方法可以做到,但如果您不需要任何花哨的东西,我想使用 标准 Java 对象序列化 就可以了.

What you want to do is called "serialization". There are several ways of doing it, but if you don't need anything fancy I think using the standard Java object serialization would do just fine.

也许你可以使用这样的东西?

Perhaps you could use something like this?

package com.example;

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

public class Serializer {

    public static byte[] serialize(Object obj) throws IOException {
        try(ByteArrayOutputStream b = new ByteArrayOutputStream()){
            try(ObjectOutputStream o = new ObjectOutputStream(b)){
                o.writeObject(obj);
            }
            return b.toByteArray();
        }
    }

    public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
        try(ByteArrayInputStream b = new ByteArrayInputStream(bytes)){
            try(ObjectInputStream o = new ObjectInputStream(b)){
                return o.readObject();
            }
        }
    }

}

对此可以进行多项改进.尤其是每个字节数组只能读/写一个对象,这可能是也可能不是您想要的.

There are several improvements to this that can be done. Not in the least the fact that you can only read/write one object per byte array, which might or might not be what you want.

请注意仅支持 java.io 的对象.Serializable 接口可以写入流"(参见 java.io.ObjectOutputStream).

Note that "Only objects that support the java.io.Serializable interface can be written to streams" (see java.io.ObjectOutputStream).

由于您可能会遇到它,java.io.ByteArrayOutputStream 可能会成为瓶颈.根据您的线程模型,您可能需要考虑重用某些对象.

Since you might run into it, the continuous allocation and resizing of the java.io.ByteArrayOutputStream might turn out to be quite the bottle neck. Depending on your threading model you might want to consider reusing some of the objects.

对于未实现 Serializable 接口的对象的序列化,您要么需要编写自己的序列化程序,例如使用 java.io.DataOutputStreamjava.nio.ByteBuffer 也许与反射一起,或引入第三方依赖.

For serialization of objects that do not implement the Serializable interface you either need to write your own serializer, for example using the read*/write* methods of java.io.DataOutputStream and the get*/put* methods of java.nio.ByteBuffer perhaps together with reflection, or pull in a third party dependency.

本站有一些序列化框架的列表和性能对比.查看 API 似乎 Kryo 可能适合您的需要.

This site has a list and performance comparison of some serialization frameworks. Looking at the APIs it seems Kryo might fit what you need.

这篇关于在java中将任何对象转换为字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆