为了保存隐形传送点,我有一个HashMap
public HashMap<Player, Location> mapHomes = new HashMap<>();它的访问方式如下:
if(cmd.getName().equalsIgnoreCase("sethome")){
Location loc = player.getLocation();
mapHomes.put(player, loc);
sender.sendMessage("Home set !");
return true;
}
if(cmd.getName().equalsIgnoreCase("home")){
Location loc1 = mapHomes.get(player);
player.teleport(loc1);
sender.sendMessage("Teleported to home");
return true;
}
return false;由于这些设置应该在重新启动时保留,因此我实现了一个save方法:
public void save(HashMap<Player,Location> mapHome, String path) throws NotSerializableException{
try{
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path));
oos.writeObject(mapHome);
oos.flush();
oos.close();
}catch(Exception e){
e.printStackTrace();
}
}但它不起作用。它抛出NotSerializableException。
我认为主要的问题是Player和Location不是可序列化的类型,那么我应该怎么写这个HashMap呢
发布于 2012-08-10 16:05:48
HashMap已经是Serializable了。
问题是map中的对象不是可序列化的,所以您也必须使它们可序列化。
public class SerializedPlayer extends Player implements Serializable {
public SerializedPlayer() {}
public SerializedPlayer(Player playerToClone) {
this.setField1(playerToClone.getField1());
// Set all the fields
}
}添加到地图时:
map.put(new SerializedPlayer(player), new SerializedLocation(location));发布于 2012-08-10 16:10:23
当实例需要有Serializable接口时,会抛出NotSerializableException。
class YourClass implements Serializable {
// ...
}发布于 2012-08-10 16:02:24
class Player implements Serializable {}
class Location implements Serializable {}请记住,您只能序列化实现Serializable接口的对象。所以您的Player和Location类也必须实现该接口。
https://stackoverflow.com/questions/11897593
复制相似问题