0

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.

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

    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;
        .......
        ...
        .


    }
4

3 に答える 3

2

ファクトリ クラス/メソッドを使用できます。あなたの場合の最も簡単な方法は、おそらくloadPlayerpublic static メソッドとして持つことです。

    public static Player loadPlayer(String GUID)
    {
        ...
        return player;
    }

それから:

Player playerVar = Player.loadPlayer(1234);
于 2013-05-21T11:41:24.327 に答える
0

あなたが説明することは不可能です。ただし、コンストラクターの代わりに (静的) ファクトリ メソッドを作成することもできます。コンストラクターは、逆シリアル化するか、新しいインスタンスを作成します。

于 2013-05-21T11:41:38.460 に答える
0

に値を割り当てることはできませんthis。不可能です。メソッドを直接呼び出さない理由loadPlayer:

Player player = Player.loadPlayer(GUID); //having loadPlayer as public static
于 2013-05-21T11:43:43.133 に答える