Immutable Exception

I am trying to create a shopping cart for a uni project. im using two classes java Element and shoppingCart, the shopping cart uses a vector to store the items and then writes them to a file. I am trying to use the classes in the jsp page, but when I try to write to a file I get java.io.WriteAbortedException: writing is aborted; java.io.NotSerializableException: cart.Item ... any ideas how I could fix this ??

+1


source to share


3 answers


From javadoc to NotSerializableException ... "Thrown when an instance is required for the Serializable interface."



This means that your class that you are serializing must implement the Serializable marker interface.

+2


source


Here's a small example for you ...



import java.io.*;

class player implements Serializable{
    String name;
    double health;
    double positionX;
    double positionY;
    int weapon;     
}


class game{
    public static void main(String[] args) throws Exception{

        player character1 = new player();
        character1.name = "Inukz";
        character1.health = 82.62;
        character1.positionX = 80;
        character1.positionY = 33;
        character1.weapon = 2;

        player character2 = new player();
        character2.name = "Prasad";
        character2.health = 32.62;
        character2.positionX = 40;
        character2.positionY = 63;
        character2.weapon = 3;


        player character3 = new player();
        character3.name = "Thilan";
        character3.health = 12.62;
        character3.positionX = 10;
        character3.positionY = 83;
        character3.weapon = 1;



        FileOutputStream fileStream = new FileOutputStream("myGame.js",true);
        ObjectOutputStream os = new ObjectOutputStream(fileStream);

        os.writeObject(character1);


        os.close();


    }

}

      

0


source


To avoid the NotSerializableException, make sure:

  • your class implements Serializable
  • all non-primitive members implement Serializable (or transient instead)
  • if your class is an inner class it is either static or the outer class implements Serializable

Also, you need to define the serialVersionUID for each Serializable class. Check all 3 cases above plus:

  • all Serializable superclasses
  • if your class is anonymous class define it there.

Note. Sometimes your code might work without serialVersionUID, but read the last paragraph in the Serializable javadoc to see why this would be a problem depending on the environment.


There is a virtual machine option to add exception details. It shows that root and nested classes cannot be serialized:

-Dsun.io.serialization.extendedDebugInfo=true

      

0


source







All Articles