I want to write a class to serialize all of the objects in my code (primitive, reference and user-defined). For the user-defined objects I have written the following code:
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
}
}
}
is it possible to reuse the same method for primitive and reference object types and what should I change in the method?
From the fact that you don't really do anything with the ID
type you can just simplify it to Object
. Also if you happen to use Java7 you can make use of the try-with-resources
statement. The FileNotFoundException
also seems to not be used. So the final version of your serialize
method would look like:
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();
}
}
That way you can call this method with what ever object you desire to serialize:
// 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]
Yes.
and reference object types
You are already doing so.
and what should I change in the method?
Nothing. Just call it with whatever you like. Autoboxing will take care of it for you.
Why you are declaring throws FileNotFoundException
from a method that cannot throw it is another mystery.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.