DAGDA SEARCH | Back to results | Support

Serializable inner class of non-serializable class — CodeQL query help documentation

Source: https://codeql.github.com/codeql-query-help/java/java-non-serializable-inner-class/

Serializable inner class of non-serializable class

ID: java/non-serializable-inner-class
Kind: problem
Security severity: 
Severity: warning
Precision: medium
Tags:
   - quality
   - reliability
   - correctness
Query suites:
   - java-security-and-quality.qls

Click to see the query in the CodeQL repository

Non-static nested classes that implement Serializable must be defined in an enclosing class that is also serializable. Non-static nested classes retain an implicit reference to an instance of their enclosing class. If the enclosing class is not serializable, the Java serialization mechanism fails with a java.io.NotSerializableException.

Recommendation

To avoid causing a NotSerializableException, do one of the following:

Example

In the following example, the class WrongSession cannot be serialized without causing a NotSerializableException, because it is enclosed by a non-serializable class. However, the class Session can be serialized because it is declared as static.

class NonSerializableServer {

    // BAD: The following class is serializable, but the enclosing class
    // 'NonSerializableServer' is not. Serializing an instance of 'WrongSession' 
    // causes a 'java.io.NotSerializableException'.
    class WrongSession implements Serializable {
        private static final long serialVersionUID = 8970783971992397218L;
        private int id;
        private String user;
        
        WrongSession(int id, String user) { /*...*/ }
    }
    
    public WrongSession getNewSession(String user) {
        return new WrongSession(newId(), user);
    }
}

class Server {

    // GOOD: The following class can be correctly serialized because it is static.
    static class Session implements Serializable {
        private static final long serialVersionUID = 1065454318648105638L;
        private int id;
        private String user;
        
        Session(int id, String user) { /*...*/ }
    }
    
    public Session getNewSession(String user) {
        return new Session(newId(), user);
    }
}

References