I'm using java appengine and the task queue API to run async tasks. I would like to add a task to the task queue but pass a a java object as a parameter. I notic the task options api can add a parameter as a byte[] but I'm unsure how to use it.
1) How would I serialize my object to a byte[]? and 2) How would the task read the byte[] and reconstruct the original object?
Thanks.
You have a few techniques to deliver the byte stream using Queue API,
Using TaskOptions.payload method
Using TaskOptions.params method
I will demonstrate how to write & read the byte stream information since there are some minor issues with google appengine implementation :)
// task is an instance of TaskOptions // Base64 - Apache implementation is being used here to encode bytes as base 64 // taskBytes - your serialized bytes
task.param("Enter-Parameter-Name", Base64.encodeBase64(taskBytes));
// Base64 - Apache implementation is being used here to encode bytes as base 64
byte[] questionsBytes = Base64.decodeBase64(request.getParameter("Enter-Parameter-Name").getBytes());
This solution works fine for me.
All the Best Uri
Turning objects into sequences of bytes and vice versa is what Serializable is made for. In the simple case, a Java class is made serializable by merely declaring it implements Serializable
.
The serialization of an object is based around introspection where the serialization code looks at the data of the serializable class and packages them in a way that describes the structure and data. Since the data stream contains the information needed to reconstruct the entire object, that's what the receiving side does.
You could look at the gory details by wrapping an ObjectOuputStream
around a ByteArrayOutputStream
, write an object to that and look at the underlying string, but you'd probably find the Object Serialization page more informative.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With