If you must use serialization for sending data over a network (instead of using a standardized XML format) don't make inner classes Serializable.
For example, the following Invoice class has an inner class called Amount.
Both implement Serializable so the Invoice can be sent via TCP/IP from one server running Windows 2000 to another server running Red Hat Linux.
/**
* Represents an invoice given to us to be paid or paid by us
*/
public class Invoice extends BaseModel
implements Serializable
{
private static final long serialVersionUID = 1715301085460067370L;
private String invoiceNumber;
private Date invoiceDate;
private Amount amountExTax;
private String status;
public static final String STATUS_PAID = "UNPAID";
public static final String STATUS_UNPAID = "PAID";
public static final String STATUS_REJECTED = "REJECTED";
:
public static class Amount implements Serializable
{
private static final long serialVersionUID = -2909366986462L;
BigInteger value;
:
}
}
Support for compiler-generated synthetic instances and serialization is not clearly defined in the Java language specs, so implementations can tend to vary, especially where a class can be serialized to data, sent over a network, and potentially deserialized using a different JVM.
So if an object is likely to be serialized, ensure it is a real class, not an inner class:
public class Amount implements Serializable
{
private static final long serialVersionUID = -2909366986462L;
BigInteger value;
:
}
Tip: Serialization, though quick, doesn't have many common uses except inside web servers where persistent session data is stored and reloaded. For most development it's safer to convert java objects to XML (using libraries like Xstream) so they can be stored or transported.