javaexceptionserializationstreamnotserializableexception

Java NotSerializableException with custom DataPackage


Im currently working on a simple server - client structure for future projects. I decided it would be the best to create my own data-package with custom header-information such as local/public ip, a time stamp etc. The following is the class i came up with:

public class DataPackage {
    private Object object;
    private Date time;
    private long timeMs;
    private boolean responded;
    private String publicIp;
    private String internalIp;
    private int hash;

    public DataPackage(Object object) {
        this.object = object;
        this.responded = false;
        this.time = Calendar.getInstance().getTime();
        this.timeMs = System.currentTimeMillis();
        this.publicIp = this.generatePublicIp();
        this.internalIp = this.generateInternalIp();
        this.hash = System.identityHashCode(this);
    }

    private String generatePublicIp() {
        try {
            URL whatismyip = new URL("http://checkip.amazonaws.com");
            BufferedReader in = new BufferedReader(new InputStreamReader(whatismyip.openStream()));

            return in.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private String generateInternalIp() {
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

}

(I removed the getters and setters)

I decided to use an object so i can send anything in the class. It compiles well but if i try to send a simple string, packaged in the class, i get a NotSerializableException. Are there any attributes or fields which cant be converted to a stream or should i change the class to be generic? Im NOT an expert in streams and networking, so im thankfull for every bit of help and explanation i can get.

NOTE: Im not a native english speaker to please excuse any spelling/grammar issues.


Solution

  • You should implement Serializable interface in order for the class to be transferred over network.

    Change first line of your class to :

    import java.io.Serializable;
    public class DataPackage implements Serializable{