Skip to content Skip to sidebar Skip to footer

Java.io.notserializableexception With "$1" After Class

I have a serialization problem and am unable to find the cause. It's an Android app in Eclipse that's giving me a very unhelpful stack trace like this: 09-01 00:06:24.414: W/System

Solution 1:

You have an anonymous inner class com.myprogram.main.Entity$1 that isn't Serializable. This is clearly stated in the exception. The $ indicates that it's an inner or static nested class that produced the exception. The digit after the $ indicates that the class is anonymous, otherwise the name of the inner class would be present here. The 1 further indicates that this is the first anonymous inner class within com.myprogram.main.Entity.

See How can I identify an anonymous inner class in a NotSerializableException for more.

Solution 2:

To work around java.io.NotSerializableException with a non-serializable anonymous inner class you can remove the anonymity and instantiate an object when necessary, which removes the need to serialize the class.

Rather than this:

classEntityimplementsSerializable {
  publicstaticvoidmain(String[] args) {
    newObject() { }; // Entity$1 <- anonymous inner class
  }
}

Do this:

classEntityimplementsSerializable {
  publicstaticvoidmain(String[] args) {
    privateclassMyClass { } // Entity$MyClass <- inner class
  }
}

If you need to serialize the MyClass objects then you still have a problem (you can make them transient to solve this), but if you don't need to (e.g. they're Runnables) then just instantiate when required like this:

classEntityimplementsSerializable {
  publicstaticvoidmain(String[] args) {
    ...
    myHandler = newHandler();
    myHandler.postDelayed(newMyRunnable(), 1000);
    ...
    privateclassMyRunnableimplements java.lang.Runnable {
      // runnable code
    }
  }
}

Post a Comment for "Java.io.notserializableexception With "$1" After Class"