Jython Is Just Too Useful

A colleague just came to me asking about Java serialization and output options. We’re going to store some partially filled Serializable DTOs in a BLOB in our database so he needed some info. Our talk then turned to options for storage and such. He already knew about using ObjectOutputStream on top of a FileOutputStream, but I also told him how to get a byte array from the object using a ByteArrayOutputStream. To illustrate, I fired up Jython in interactive mode and typed the following:

[c:tmp] jython
*sys-package-mgr*: processing modified jar, 'C:AspectJ1.1libaspectjrt.jar'
Jython 2.1 on java1.3.1_02 (JIT: null)
Type "copyright", "credits" or "license" for more information.
>>> from java.io import *
>>> from java.util import*
>>> m = ArrayList()
>>> m.add("Foo")
1
>>> m.add("Bar")
1
>>> m
[Foo, Bar]
>>> baos = ByteArrayOutputStream()
>>> oos = ObjectOutputStream(baos)
>>> oos.writeObject(m)
>>> oos.close()
>>> dir(baos.class)
['__init__', 'reset', 'size', 'toByteArray', 'toString', 'write', 'writeTo']
>>> baos.toByteArray()
array([-84, -19, 0, 5, 115, 114, 0, 19, 106, 97,
  118, 97, 46, 117, 116, 105, 108, 46, 65, 114, 114,
  97, 121, 76, 105, 115, 116, 120, -127, -46, 29,
  -103, -57, 97, -99, 3, 0, 1, 73, 0, 4, 115, 105,
  122, 101, 120, 112, 0, 0, 0, 2, 119, 4, 0, 0, 0,
  10, 116, 0, 3, 70, 111, 111, 116, 0, 3, 66, 97,
  114, 120], byte)
>>> bais = ByteArrayInputStream(baos.toByteArray())
>>> ois = ObjectInputStream(bais)
>>> x = ois.readObject()
>>> x
[Foo, Bar]
>>> m
[Foo, Bar]

There are lots of cool things there, but specifically, notice the bits in red. I couldn’t remember the method to call to get the byte array, so by using the Python dir() method on the class of the object, I got a list of available methods. toByteArray() was the ticket and you can see both the array itself and then that I went further and deserialized the byte array using a ByteArrayInputStream. Think about how many lines of Java code I would have had to write to show him the same thing. But even if the syntax were just as verbose as Java, not having an edit-compile-run cycle made the demo far faster and productive than it would have otherwise been.