Java:具有可复制成员的Runnable成员的对象的深层复制

时间:2018-10-14 19:02:26

标签: java copy-constructor runnable deep-copy

我有一个character类,我想在某个事件之前创建一个副本,这样,如果用户搞砸了,他可以重试该副本。为此,我使用如下的复制构造函数:

public class character
    implements Serializable
{
private String                          name;
private HashMap<String,Integer>         values = new HashMap<>();
private ArrayList<String>               traits = new ArrayList<>();
private enums.playerRelations           playerRelation;
private static character                playerCharacter = new character();
private transient Runnable              combatAI;
private transient Runnable              tradingAI;
private ArrayList<character>            companions = new ArrayList<>();
private ArrayList<item>                 inventory = new ArrayList<>();
private int                             maximumInventorySize = 20;
private int                             maximumSkillSlots = 10;
private transient ArrayList<Pair<skill,Boolean>>  skills = new ArrayList<>();
private int                             portraitResource = R.drawable.ic_bear;
private event                           eventContext;

public character(character o)
{
    name                    = o.name;
    values                  = new HashMap<>(o.values);
    traits                  = new ArrayList<>(o.traits);
    playerRelation          = o.playerRelation;
    combatAI                = o.combatAI;
    tradingAI               = o.tradingAI;
    companions              = new ArrayList<>(o.companions);
    inventory               = new ArrayList<>(o.inventory);
    maximumInventorySize    = o.maximumInventorySize;
    maximumSkillSlots       = o.maximumSkillSlots;
    skills                  = new ArrayList<>(o.skills);
    portraitResource        = o.portraitResource;
    eventContext            = o.eventContext;
}

// ...
}

但是,我不知道如何深度克隆Runnable对象。我该如何深层复制这些内容?使用复制构造函数完全可以吗?

我注意到Runnablecharacter的其他成员是不同的,因为关注的部分存储在函数而不是属性中...

1 个答案:

答案 0 :(得分:1)

如果您仅知道combatAIRunnable,那么您就无法对其进行深度复制-可以说它没有深度-仅{{1} }。

您可能需要重新考虑这种方法,并在游戏(?)中明确拥有检查点,以便可以根据检查点数据创建Runnable和其余状态。

还请注意,您的combatAI副本仅一层深,原始inventory和新character共享相同的item。与companions

相同