当前位置: 代码迷 >> java >> Java动态创建类实例
  详细解决方案

Java动态创建类实例

热度:26   发布时间:2023-07-31 11:07:47.0

我正在做一个小型纸牌游戏。 在此游戏中,新玩家是扩展通用玩家类的AIPlayer或HumanPlayer类的实例。

当前要生成播放器,我有以下代码:

private List<Player> players;

HumanPlayer playerA = new HumanPlayer("playerA");
playerA.addObserver(gameModelObserver);
players.add(playerA);

AIPlayer playerB = new AIPlayer("playerB");
playerB.addObserver(gameModelObserver);
players.add(playerB);

AIPlayer playerC = new AIPlayer("playerC");
playerC.addObserver(gameModelObserver);
players.add(playerC);

HumanPlayer playerD = new HumanPlayer("playerD");
playerD.addObserver(gameModelObserver);
players.add(playerD);

是否可以动态生成这些类? 我可以做一些类似的事情,用一个播放器名称和一个布尔值遍历链表的所有元素,以指示它们是AI还是Human,然后为它们生成类的实例。 如果是这样,怎么办?

编辑:为了更清楚,我正在寻找这样的事情是否可能:

for(int i=0; i<x; i++){
player i = new Player("i");
i.addObserver(gameModelObserver);
players.add(i); }

这不能回答您的问题,但是可以解决您的问题:

private List<Player> players;

public void createPlayerByName(String name, Class type) {
  Player player = type.equals(HumanPlayer) ? new HumanPlayer(name) : new IAPlayer(name);
  player.addObserver(gameModelObserver);
  players.add(player);
}

public void createHumanPlayerByName(String name) {
  createPlayerByName(name, HumanPlayer.class);
}

public void createIAPlayerByName(String name) {
  createPlayerByName(name, AIPlayer.class);
}

因此,使用您的列表,您只需要执行以下操作:

for (String name : humanNameList) {
  createHumanPlayerByName(name);
}

for (String name : aiNameList) {
  createAIPlayerByName(name);
}

大概是这样的:

class Player {

    String name;
    Type type;

    public Player(String name, Type type) {
        this.name = name;
        this.type = type;
    }
}

Player[] playersList = { new Player("playerA", Type.HUMAN), new Player("playerB", Type.AI)};
for (Player player: playersList) {
    if (player.type == Type.AI) {
            AIPlayer aiPlayer = AIPlayer.class.getConstructor(String.class).newInstance(player.name);
            aiPlayer.addObserver(gameModelObserver);
            players.add(aiPlayer);                                    }
    else {
            HumanPlayer humanPlayer = HumanPlayer.class.getConstructor(String.class).newInstance(player.name);
            humanPlayer.addObserver(gameModelObserver);
            players.add(humanPlayer);
    }

}
  相关解决方案