1

I have an abstract Entity

public class Entity<ID> {
    private ID id;
    public ID getId() {
        return id;
    }
    public void setId(ID id) {
        this.id = id;
    }
}

And a User which inherits from Entity

public class User extends Entity<Long> implements Serializable {
    private String name;
    private String email;

    private List<String> friends;

    public User(Long ID, String name, String email) {
        this.setId(ID);
        this.name = name;
        this.email = email;
        this.friends = new ArrayList<>();
    }
}

The client creates a connection with the server and ask for a User. The server responses like this: In main method:

try (ServerSocket ss = new ServerSocket(6666)) {
    while (true) {
        Socket s = ss.accept();
        Thread t = new ServeConnection(s);
        t.start();
    }
}

...
private static class ServeConnection extends Thread {
    public ServeConnection(Socket s) {
        this.s = s;
    }

    public void run() {
        try (ObjectInputStream is = new ObjectInputStream(s.getInputStream());
        ObjectOutputStream os = new ObjectOutputStream(s.getOutputStream())) {
        ...
        User u = new User(1, "Name", "Email@gmail.com");
        os.writeObject(u);
    }
}

The client reads the object but the id is set to null

...
User u = (User) is.readObject();
System.out.println(u); // id=null, name="Name", email="Email@gmail.com"

Why is the id set to null? Thank you

Enowneb
  • 943
  • 1
  • 2
  • 11
Flaviu
  • 51
  • 4

1 Answers1

3

The problem was that both User and Entity need to implement Serializable

Flaviu
  • 51
  • 4