Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing objects with the Java Preferences API

When I first started using the Java Preferences API, the one glaring omission from the API was a putObject() method. I've always wondered why they did not include it.

So, I did some googling and I found this article from IBM which shows you how to do it: http://www.ibm.com/developerworks/library/j-prefapi/

The method they're using seems a bit hackish to me, because you have to break the Object up into byte matrices, store them, and reassemble them later.

My question is, has anyone tried this approach? Can you testify that it is a good way to store/retrieve objects?.

I'm also curious why the Java devs left putObject() out of the API. Does anyone have valuable insight?

like image 216
ryvantage Avatar asked Jul 11 '26 07:07

ryvantage


2 Answers

I'm also curious why the Java devs left putObject() out of the API. Does anyone have valuable insight?

From: http://docs.oracle.com/javase/7/docs/technotes/guides/preferences/designfaq.html

Why doesn't this API contain methods to read and write arbitrary serializable objects?

Serialized objects are somewhat fragile: if the version of the program that reads such a property differs from the version that wrote it, the object may not deserialize properly (or at all). It is not impossible to store serialized objects using this API, but we do not encourage it, and have not provided a convenience method.

like image 173
Puce Avatar answered Jul 13 '26 22:07

Puce


The article describes a reliable way to do it. I see there are a couple of things I may do differently (like I would store the count of the number of pieces as well as the pieces themselves so that I can figure things out easily when I retrieve them).

Your comment about Serialization is wrong though.... the object you want to store has to be Serializable.... that's how the ObjectOutputStream that the document uses does it's job.

So, Yes, it looks like a reliable mechanism, you need to have Serializable objects, and I imagine that the reason that putObject and getObject are not part of the API for two reasons:

  1. it's not part of the way that is native to Windows registries
  2. It risks people putting huge amounts of data in the registry.

Storing serialized objects in the registry strikes me as being somewhat concerning because they can be so big. I would only use it for occasions when there is no way to reconstruct the Object from constructors, and the serialized version is relatively small.

like image 22
rolfl Avatar answered Jul 13 '26 22:07

rolfl



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!