0

I'm trying to cast object from ObjectInputStream to object that already exists in my class:

//main class
Tester tester = new Tester();
tester.setHeight(50);
tester.setWidth(100);

/*FileOutputStream fs = new FileOutputStream("data.txt");
  ObjectOutputStream os = new ObjectOutputStream(fs);
  os.writeObject(tester);
  os.close();*/

FileInputStream fis = new FileInputStream("data.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
Tester x = (Tester) ois.readObject();
System.out.println(x.getHeight() + " " + x.getWidth());

I'm getting:

java.io.InvalidClassException: Tester; local class incompatible: stream classdesc serialVersionUID error.

Maor
  • 3,340
  • 3
  • 29
  • 38
  • BTW, `Tester x = new Tester(); x = (Tester) ois.readObject();` can be simplified to `Tester x = (Tester) ois.readObject();`. Even if you don't simplify it, you shouldn't instantiate a new `Tester` instance for no reason. – SOFe Sep 09 '16 at 16:11
  • do you have a `serialVersionUID` field in your `Tester` class? Should look like `private static final long serialVersionUID = 2873572398493427L;` or something like that – Orin Sep 09 '16 at 16:17
  • @Orin2005 Tester implements Serializable.. – Maor Sep 09 '16 at 16:18
  • @Maor it should have a serialVersionUID as well. – Orin Sep 09 '16 at 16:19
  • @Orin2005 It doesn't *need* one. You can create a Serializable class without one, although it's not recommended. – Kayaman Sep 09 '16 at 16:19
  • @Kayaman yes he doesnt need one, but its probably exactly why he is running into this error I believe. Moar check out this link for more information: http://stackoverflow.com/questions/285793/what-is-a-serialversionuid-and-why-should-i-use-it – Orin Sep 09 '16 at 16:22

0 Answers0