shrini1000
shrini1000

Reputation: 7236

Java serialization: access modifier for readResolve()

Java documentation for the above says:

ANY-ACCESS-MODIFIER Object readResolve() throws ObjectStreamException; 

but I've often seen it defined as 'protected'.

Similarly for:

ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L; 

I've seen it defined as 'public'.

Any thoughts on why Java kept it so open here, and what should they be defined as in professional code?

Upvotes: 0

Views: 372

Answers (1)

Joachim Sauer
Joachim Sauer

Reputation: 308239

I'd define both of those as private: No code has any reason to access those methods/fields, only the JVM should access it.

Why has it been designed this way? I can only guess here, but if the methods/fields are accessed only by the JVM, then adding a check for the correct access modifier would only add to the complexity without gaining too much technical advantage.

Upvotes: 1

Related Questions