[英]How to deserialize object from constructor in Java?
I am trying to do some funky stuff which i have never done before. 我正在尝试做一些我以前从未做过的时髦的东西。
So what i am trying to do is: I create an object by doing the following 所以我想要做的是:我通过执行以下操作创建一个对象
Player playerVar = new Player(1234);
Players constructor will then look for a player called 1234
, if it exists, it will then deserialize and store the loaded object under 'playerVar
' , if not it'll just follow through and give a
'blank'` player object. 然后玩家构造函数将寻找一个
called 1234
的玩家,如果它存在,它将反序列化并将加载的对象存储在'playerVar
'下, if not it'll just follow through and give a
'blank'`玩家对象。
I am not sure if its even possible to make the current object an other instance of the same object, so i am posting here. 我不确定它是否可能使当前对象成为同一对象的另一个实例,所以我在这里发帖。
This is essentially what i am trying to do. 这基本上就是我想要做的。
this = deserielizedObject
I know this can all be done by loading the object, then setting all the necessary variables manually, but that is hardly ideal. 我知道这一切都可以通过加载对象,然后手动设置所有必要的变量来完成,但这并不理想。 How can i 'replace' an object with another instance of itself, from within itself
我怎样才能从一个内部替换另一个自身实例
This is the code i currently have 这是我目前的代码
player.java player.java
public class Player implements java.io.Serializable
{
Player(String GUID) // when loading a new player
{
Player player = loadPlayer(GUID);
//i want to set this to player
// something like this = player If you know what i mean....
}
Player()//when creating a new player
{
}
private Player loadPlayer(String GUID)
{
File f = new File("data/players/"+GUID+".ser");
if(!f.exists())
{
Player player = new Player();
return player;
}
Player player = null;
try
{
FileInputStream fileIn = new FileInputStream("data/players/"+GUID+".ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
player = (Player) in.readObject();
in.close();
fileIn.close();
}
catch(IOException i)
{
i.printStackTrace();
return null;
}
catch(ClassNotFoundException c)
{
System.out.println("Cant find Player Class!");
c.printStackTrace();
return null;
}
return player;
}
private int guid;
private String name;
private int bankMoney;
.......
...
.
}
You could use a factory class/method. 您可以使用工厂类/方法。 The simpliest way in your case would probably be to just have
loadPlayer
as a public static method. 在您的情况下最简单的方法可能是将
loadPlayer
作为公共静态方法。
public static Player loadPlayer(String GUID)
{
...
return player;
}
then: 然后:
Player playerVar = Player.loadPlayer(1234);
What you describe is not possible. 你所描述的是不可能的。 But you could create a (static) factory method instead of the constructor, which either deserializes or creates a new instance.
但是你可以创建一个(静态)工厂方法而不是构造函数,它可以反序列化或创建一个新实例。
You cannot assign a value to this
, not possible. 您无法
this
分配值, this
不可能的。 Why not directly call the loadPlayer
method: 为什么不直接调用
loadPlayer
方法:
Player player = Player.loadPlayer(GUID); //having loadPlayer as public static
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.