Search code examples
javaserializationcompiler-errorsserializable

cannot find symbol Serializable?


Why does this:

package com.example;

import com.example.Foo.Bar.Baz;

import java.io.Serializable; // I did import Serializable...

public class Foo implements Serializable {

    public final Bar bar;

    public Foo(Bar bar) {
        this.bar = bar == null ? new Bar(Baz.ONE) : bar;
    }

    public static class Bar implements Serializable { // this is line 15, where the compiler error is pointing 

        public enum Baz {
            ONE
        }

        public final Baz baz;

        public Bar(Baz baz) {
            this.baz = baz;
        }
    }

}

Give me this:

[ERROR] <path to file>/Foo.java:[15,44] cannot find symbol
[ERROR] symbol:   class Serializable
[ERROR] location: class com.example.Foo

If I replace the Serializable interface to something else like :

public interface MyMarkerInterface {}

then the code compiles. (even Cloneable works!)

What makes this happen? intelliJ didn't spot anything wrong through static analysis.


Solution

  • Don't try and import the internal class. That's causing your compiler error

    // import com.example.Foo.Bar.Baz;
    import java.io.Serializable;
    
    public class Foo implements Serializable {
        public final Bar bar;
    
        public Foo(Bar bar) {
            this.bar = bar == null ? new Bar(Bar.Baz.ONE) : bar;
        }
    
        public static class Bar implements Serializable {
            public enum Baz {
                ONE
            }
            public final Baz baz;
            public Bar(Baz baz) {
                this.baz = baz;
            }
        }
    }