NullPointerException when trying to write object instance to
ObjectOutputStream
I'm getting
Exception in thread "main" java.lang.NullPointerException
at java.io.FileOutputStream.<init>(FileOutputStream.java:201)
at java.io.FileOutputStream.<init>(FileOutputStream.java:99)
at lib.Entry.serialize(Entry.java:17)
at main.Main.main(Main.java:8)
Where Entry.java:17 is stream.writeObject(this); (see below)
Entry.java
package lib;
import java.io.*;
public class Entry { // Superclass.
String filename; // Set below.
String name; // Set by the subclass.
public void main() {
this.filename = this.name + ".ser";
serialize();
}
public void serialize() {
try {
FileOutputStream file = new FileOutputStream(this.filename);
ObjectOutputStream stream = new ObjectOutputStream(file);
stream.writeObject(this);
stream.close();
file.close();
System.out.println("Serialized.");
} catch(IOException e) {
e.printStackTrace();
}
}
}
Place.java
package lib;
public class Place extends lib.Entry { // A subclass.
public String name;
public Place(String name) {
this.name = name;
}
}
Main.java
package main;
import lib.Place;
public abstract class Main {
public static void main(String[] args) {
Place room = new Place("room");
room.serialize();
}
}
Why am I getting a NullPointerException when using this? I'm trying to
write the current object instance to the ObjectOutputStream. I'm new to
Java and I have no idea how to proceed. In Python I'd use something like
stream.writeObject(self) so by the same line of thought I used this in
Java. I tried using stream.writeObject(Object this);, but it didn't work.
I also tried
Object p = this;
stream.writeObject(p);
Which I guess is the same thing. It also didn't work. The idea is to have
more classes (other than Place) extending Entry, allowing them to be
serialized using the Entry.serialize() method.
No comments:
Post a Comment