所以我有这些我无法更改的类,我需要使用这些类来将序列化对象发送到服务器。但是我对枚举没有太多经验,并且很难理解如何做到这一点?
import java.io.Serializable;
public abstract class Message implements Serializable {
private static final long serialVersionUID = 0L;
private final MessageType type;
public Message(MessageType type) {
this.type = type;
}
public MessageType getType() {
return type;
}
@Override
public String toString() {
return type.toString();
}
}
public final class CommandMessage extends Message {
private static final long serialVersionUID = 0L;
private final Command cmd;
public CommandMessage(Command cmd) {
super(MessageType.COMMAND);
this.cmd = cmd;
}
public Command getCommand() {
return cmd;
}
public static enum Command {
LIST_PLAYERS, EXIT, SURRENDER;
private static final long serialVersionUID = 0L;
}
}
我最了解序列化,这是一个简单的tictactoe游戏,我有一个后台线程运行来接收对象。但是如何命令发送到服务器?假设我想看一个播放器列表,我如何制作commandMessage对象以便我可以发送它?我想我错过了一些非常简单的> _<
public static void main(String[]args) throws IOException{
//make tictactoe client
TicTacToeClient newClient = new TicTacToeClient();
//start run
newClient.run();
//start a connection, send username
ConnectMessage connect = new ConnectMessage("User17");
newClient.out.writeObject(connect);
CommandMessage newComm = new CommandMessage(); //what!? HOW?
//s.BOARD = PLAYERLIST;???
//NOPE.
//PlayerListMessage playerList = new PlayerListMessage();
System.out.println();
}
答案 0 :(得分:0)
您必须使用构造函数
CommandMessage newComm = new CommandMessage(CommandMessage.Command.LIST_PLAYERS);
或使用提供的其他枚举