Java: Save Object for Later Use

1.6k Views Asked by At

Pulling the data from the server (using SOAP methods) is slow and I would like that the program loads with the object already present. I tried the code I found here, but it raises a java.io.NotSerializableException

Now I need the data to remain intact. Is there any way to save it without modifying it?

There were other answers in that post about how to serialize the data, but I am afraid that will skew the results I get with the static object.

3

There are 3 best solutions below

0
On

java.io.NotSerializableException - This happens if your class isn't implementing Serializable. Object of Serializable class will be written in file as sequence of bytes containing all information of that object.

If you don't want to use it then there are other ways to serialize object like JSON or MessagePack ... Just do research and find one that fits your needs best.

0
On

You can use a JSON serializer like Jackson to do this. Ideally the object would have relevant getters for the data you mention that you need to remain intact. Even if the data is private, you can tell Jackson to serialize it anyways using reflection.

ObjectMapper mapper = new ObjectMapper();

// You can use these options if the object doesn't have getters
// for fields that need to be saved, and the fields are private. 
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);

// Save the string representation somewhere
String yourObjectAsAJsonString = mapper.writeValueAsString(yourObject);

// Load the object back from the string representation
YourObject yourObjectDeserialized = mapper.readValue(yourObjectAsAJsonString, YourObject.class);

Your issue with the java.io.NotSerializableException is probably not under your control because you are receiving the object via SOAP, so you can't make it implement Serializable after the fact. Using a JSON serializer like Jackson can help you get around this problem.

0
On

I think your problem is not related to SOAP or data transfer but just Java serialization. Is your class serializable? Can you write a simple main method writing and reading your instance into a file or a ByteArrayOutputStream? See here.

If/when your object is serializable you need to separate the data reading from the deserialization part. Use a ByteArrayOutputStream to collect the data (or a temporary file for very large data) and do the deserialization when the data transfer is completed.

The overall process won't be faster and this will not solve any serialization/deserialization errors, it just allows to separate the two parts allowing you to use different threads or asynchio to better utilize the server resources.