-5

What does java serialize for an object?

static fields?

non static fields?

methods prototype?

methods body?

Dan Dinu
  • 32,492
  • 24
  • 78
  • 114

4 Answers4

4

By default, with the built-in stuff?

Nonstatic (nontransient) fields, a reference to the class (which fully determines the method prototypes and bodies), and nothing else.

Custom serialization can do whatever you want, but serialization is supposed to write a single instance object, which certainly rules out static methods or variables...

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
3

Methods aren't serialized because they are from the class definition itself. Static fields aren't serialized because they, once more, doesn't belong to the instance itself but the class (what would be the meaning to serialize something within each instance when just one if the serialized values could be applied to the other side?). So the answer is just fields.

But even for fields, there is the case in which the file is qualified as transient and these will not be serialized. For instance:

public class T implements Serializable {
   transient int i = 0;
}

In this case, i will not be serialized and each deserialized instance will present i with value 0.

Francisco Spaeth
  • 23,493
  • 7
  • 67
  • 106
2

static fields?

no

non static fields?

Provided they are not transient and the class implement Serializable

methods prototype?

no

methods body?

no.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

It serializes instance data, not static data or methods. There are a number of ways to tweak the data saved, using the transient keyword, the Externalizable interface, and a few other things.

Critically, if an object references other objects, directly or indirectly, all those other objects will be serialized also. So serializing one object can result in serializing millions of them. It's a powerful tool, for good and evil.

Also, if you write more than one object to ObjectOutputStream, and one object's already been written, directly or indirectly, only a reference will be sent to the stream. On being read, the new object will contain the data from the first write. This isn't a problem when writing to files, but (along with the heavy memory usage) can be embarrassing when writing to a socket. (It embarrassed me, anyway. Hint: use the reset() method.)

RalphChapin
  • 3,108
  • 16
  • 18