2

たとえばMyStaticClass、静的クラスがあるとします。これには、たとえば次のように、ファイルとの間で自身を保存およびロードするための2つのメソッドがあります。

private static void save() throws IOException {
  FileOutputStream fos = new FileOutputStream(new File("myfile.dat"));
  ObjectOutputStream oos = new ObjectOutputStream(fos);
  oos.writeObject(???);
  oos.close();
}

private static void load() throws IOException {
  FileInputStream fis = new FileInputStream(new File("myfile.dat"));
  ObjectInputStream ois = new ObjectInputStream(fis);
  ??? = (MyStaticClass) ois.readObject();
  ois.close();
}

???通常オブジェクトのインスタンスを配置する場所の代わりに何を配置する必要がありますか?

インスタンスに使用されているものとは異なる静的クラスをファイルに保存する方法はありますか?

4

2 に答える 2

4

私が知っている限り、あなたはそのようにそれをすることはできません。ただし、クラス全体を一度に作成するのではなく、静的フィールドを個別に作成することもできます。

例えば。

public class MyClass() {

    private static String staticField1;
    private static String staticField2;

    static {
        load();
    }

    private static void saveField(String fieldName, Object fieldValue) throws IOException {
      FileOutputStream fos = new FileOutputStream(new File("MyClass-" + fieldName + ".dat"));
      ObjectOutputStream oos = new ObjectOutputStream(fos);
      oos.writeObject(fieldValue);
      oos.close();
    }


    private static Object readField(String fieldName) throws IOException {
      FileInputStream fis = new FileInputStream(new File("MyClass-" + fieldName + ".dat"));
      ObjectInputStream ois = new ObjectInputStream(fis);
      Object value = ois.readObject();
      ois.close();

      return value;
    }

    private static void save() throws IOException {
      saveField("staticField1", staticField1);
      saveField("staticField2", staticField2);
    }

    private static void load() throws IOException {
      staticField1 = (String)readField("staticField1");
      staticField2 = (String)readField("staticField2");
    }

}
于 2013-03-25T16:34:17.773 に答える
1

「静的クラス」とはどういう意味かわかりません。クラスの状態が静的データメンバーのみで構成されている場合は、これらのデータメンバーをsave()メソッドに格納し、loadメソッドで更新します。

一方、保存したい非静的状態がある場合は、saveメソッドは静的ではなく、loadメソッドは静的である必要があり、新しいインスタンスを返すように見えます。

于 2013-03-25T16:45:08.953 に答える