rspec/rules/S2062/java/rule.adoc

67 lines
1.7 KiB
Plaintext

== Why is this an issue?
Developers may want to add some logic to handle deserialized objects before they are returned to the caller.
This can be achieved by implementing the `readResolve` method.
Non-final classes implementing `readResolve` should not set its visibility to `private` as this would make it unavailable to child classes.
Instead, mark `readResolve` as `protected`, allowing it to be inherited.
=== Code examples
==== Noncompliant code example
[source,java,diff-id=1,diff-type=noncompliant]
----
public class Fruit implements Serializable {
private static final long serialVersionUID = 1;
private Object readResolve() throws ObjectStreamException // Noncompliant, `readResolve` should not be private
{...}
//...
}
public class Raspberry extends Fruit implements Serializable { // This class has no access to the parent's "readResolve" method
//...
}
----
==== Compliant solution
[source,java,diff-id=1,diff-type=compliant]
----
public class Fruit implements Serializable {
private static final long serialVersionUID = 1;
protected Object readResolve() throws ObjectStreamException // Compliant, `readResolve` is protected
{...}
//...
}
public class Raspberry extends Fruit implements Serializable { // This class has access to the parent's "readResolve"
//...
}
----
== Resources
* https://docs.oracle.com/javase/8/docs/platform/serialization/spec/input.html#a5903[Java Object Serialization Specification - Object Input Classes]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Make this class "private" or elevate the visibility of "readResolve".
endif::env-github,rspecator-view[]