Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize any Object

Tags:

java

I tried doing this:

ByteArrayOutputStream b = new ByteArrayOutputStream();
ObjectOutputStream o = new ObjectOutputStream(b);
o.writeObject(obj); 

Where obj is a simple class I made:

class Car {
  int id;
  String color;
  //... 
}

However I get java.io.NotSerializableException

Is it possible to serialize just about any kind of java.lang.Object into byte array? Is so, how?

Update:

The class that will be "serialized" does not implement a Serializable interface; the idea behind this thing I am trying to do is that I'm trying to have a Databse-backed java.util.Map where objects put in the map are stored directly in the database, thus any kind of Object

I have also seen some Serialization framework, where to get around this "limitation" in serializing arbitrary Object, there is a class registration like:

kryo.register(SomeClass.class, 0); 

Not sure about this.

But what I'm quite sure is that I need to do:

  • Reflection to read fields and methods of an Object

2 Answers

Your Car class needs to implement the Serializable interface for you to be able to Serialize your object.

class Car implements Serializable {
like image 181
Rahul Avatar answered Sep 21 '26 08:09

Rahul


It's not possible to use a java.io.ObjectOutputStream to serialize every Object.

From the javadoc of ObjectOutputStream

Only objects that support the java.io.Serializable interface can be written to streams.

If you absolutely need java objects serialization kryo worths a try. By default you just need to do:

Kryo kryo = new Kryo();
// ...
Output output = new Output(new FileOutputStream("file.bin"));
SomeClass someObject = ...
kryo.writeObject(output, someObject);
output.close();

Kryo doesn't require your classes to implement Serializable and you can provide separate Serializer for your classes to control the serialization form. But is optional.

The code kryo.register(SomeClass.class, 0); is optional too, it optimize the serialization process.

like image 35
dcernahoschi Avatar answered Sep 21 '26 07:09

dcernahoschi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!