68 lines
1.8 KiB
Plaintext
68 lines
1.8 KiB
Plaintext
== Why is this an issue?
|
|
|
|
Non-static inner classes contain a reference to an instance of the outer class.
|
|
Hence, serializing a non-static inner class will result in an attempt at serializing the outer class as well.
|
|
If the outer class is not serializable, serialization will fail, resulting in a runtime error.
|
|
|
|
Making the inner class `static` (i.e., "nested") avoids this problem, as no reference to an instance of the outer class is required.
|
|
Serializing the inner class can be done independently of the outer class.
|
|
Hence, inner classes implementing `Serializable` should be `static` if the outer class does not implement `Serializable`.
|
|
|
|
Be aware of the semantic differences between an inner class and a nested one:
|
|
|
|
* an inner class can only be instantiated within the context of an instance of the outer class.
|
|
* a nested (`static`) class can be instantiated independently of the outer class.
|
|
|
|
|
|
== How to fix it
|
|
|
|
Make the inner class `static` or make the outer class `Serializable`.
|
|
|
|
|
|
=== Code examples
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,java,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
public class Pomegranate {
|
|
// ...
|
|
|
|
public class Seed implements Serializable { // Noncompliant, serialization will fail due to the outer class not being serializable
|
|
// ...
|
|
}
|
|
}
|
|
----
|
|
|
|
|
|
==== Compliant solution
|
|
|
|
[source,java,diff-id=1,diff-type=compliant]
|
|
----
|
|
public class Pomegranate {
|
|
// ...
|
|
|
|
public static class Seed implements Serializable { // Compliant, the outer class will not be serialized and hence cannot be the cause for a failure at runtime
|
|
// ...
|
|
}
|
|
}
|
|
----
|
|
|
|
|
|
== Resources
|
|
|
|
* https://wiki.sei.cmu.edu/confluence/x/ZTdGBQ[CERT SER05-J.] - Do not serialize instances of inner classes
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
Make this inner class static
|
|
|
|
|
|
endif::env-github,rspecator-view[]
|