65 lines
1.7 KiB
Plaintext
65 lines
1.7 KiB
Plaintext
== Why is this an issue?
|
|
|
|
Serialization is a platform-independent mechanism for writing the state of an object into a byte-stream. For serializing the object, we
|
|
call the `writeObject()` method of `java.io.ObjectOutputStream` class.
|
|
Only classes that implement `Serializable` or extend a class that does it can successfully be serialized (or de-serialized).
|
|
|
|
Attempting to write a class with the `writeObject` method of the `ObjectOutputStream` class that does not implement `Serializable` or
|
|
extends a class that implements it, will throw an `IOException`.
|
|
|
|
== How to fix it
|
|
|
|
The object class passed as an argument to the `writeObject` must implement `Serializable`.
|
|
|
|
=== Code examples
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,java,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
public class Vegetable {
|
|
// ...
|
|
}
|
|
|
|
public class Menu {
|
|
public void meal(ObjectOutputStream oos) throws IOException {
|
|
Vegetable veg = new Vegetable();
|
|
oos.writeObject(veg); // Noncompliant
|
|
}
|
|
}
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,java,diff-id=1,diff-type=compliant]
|
|
----
|
|
public class Vegetable implements Serializable {
|
|
// ...
|
|
}
|
|
|
|
public class Menu {
|
|
public void meal(ObjectOutputStream oos) throws IOException {
|
|
Vegetable veg = new Vegetable();
|
|
oos.writeObject(veg);
|
|
}
|
|
}
|
|
----
|
|
|
|
== Resources
|
|
* https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/io/Serializable.html[Oracle Java SE - Serializable]
|
|
* https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/io/ObjectOutputStream.html[Oracle Java SE - ObjectOutputStream]
|
|
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
* Make the "xxx" class "Serializable" or don't write it.
|
|
|
|
|
|
endif::env-github,rspecator-view[]
|