是否可以将 java 原始和引用对象类型转换为与用户定义对象相同的字节数组?

Is it possible to convert java primitive and reference object types to a byte array as same as user-defined objects?

我想写一个 class 来序列化我代码中的所有对象(原始、引用和用户定义)。对于用户定义的对象,我编写了以下代码:

static void serialize(Object object, OutputStream outputStream) {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutput objectOutput = null;
    try {
        objectOutput = new ObjectOutputStream(bos);
        objectOutput.writeObject(object);
        objectOutput.flush();
        byte[] bytes = bos.toByteArray();
        outputStream.write(bytes);

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            outputStream.close();
            bos.close();
        } catch (IOException ex) {
            // ignore close exception
        }
    }
}

是否可以对原始对象类型和引用对象类型重用相同的方法?我应该在方法中更改什么?

由于您实际上并没有对 ID 类型做任何事情,因此您可以将其简化为 Object。此外,如果您碰巧使用 Java7,您可以使用 try-with-resources 语句。 FileNotFoundException 好像也不能用。所以你的 serialize 方法的最终版本看起来像:

static void serialize(Object o, OutputStream outputStream){
    try(ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
        ObjectOutput objectOutput = new ObjectOutputStream(bos)){
        objectOutput.writeObject(o);
        objectOutput.flush();
        byte[] bytes = bos.toByteArray();
        outputStream.write(bytes);
    } catch (IOException e) {
        e.printStackTrace();
    } 
}

这样你就可以用你想要序列化的任何对象调用这个方法:

// With String
serialize("Hello World!", out);

// With int
serialize(2547, out);

// with byte-array
serialize(new byte[]{1,3,5,6}, out);

// with userdefined object
serialize(new MyObject(), out);

is it possible to reuse the same method for primitive [types]

是的。

and reference object types

您已经在这样做了。

and what should I change in the method?

没有。随心所欲地称呼它。自动装箱会为您处理。

为什么要从无法抛出它的方法中声明 throws FileNotFoundException 是另一个谜。