0

所以我有这些我无法更改的类,我需要使用这些类将序列化对象发送到服务器。但是我对枚举没有太多经验,并且很难理解如何做到这一点?

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();       
}
4

1 回答 1

0

您必须使用构造函数

CommandMessage newComm = new CommandMessage(CommandMessage.Command.LIST_PLAYERS);

或使用提供的其他枚举之一

于 2014-11-18T23:36:22.677 回答