Created
May 15, 2016 16:14
-
-
Save MaksimDmitriev/1808e3a7be43dffcba6d701b384b2eda to your computer and use it in GitHub Desktop.
Enum Serialization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package etf; | |
public class A { | |
public int t; | |
A(int t) { | |
this.t = t; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package etf; | |
public enum E { | |
E1(new A(50)), E2(new A(100)); | |
public A a; | |
E(A a) { | |
this.a = a; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package etf; | |
import java.io.FileInputStream; | |
import java.io.FileOutputStream; | |
import java.io.IOException; | |
import java.io.ObjectInputStream; | |
import java.io.ObjectOutputStream; | |
public class Main { | |
public static void main(String[] args) { | |
E e = E.E1; | |
e.a.t = 2365; | |
E e11 = E.E1; | |
System.out.println(e11.a.t); // 2365 'cause there is only one instance of E1 | |
write(); | |
read(); | |
} | |
private static void read() { | |
ObjectInputStream objectInputStream = null; | |
try { | |
objectInputStream = new ObjectInputStream(new FileInputStream( | |
"storage.txt")); | |
E e = (E) objectInputStream.readObject(); | |
System.out.println(e.a.t); // 51 'cause there is only one instance of E2 | |
} catch (IOException e) { | |
} catch (ClassNotFoundException e) { | |
e.printStackTrace(); | |
} finally { | |
if (objectInputStream != null) { | |
try { | |
objectInputStream.close(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
} | |
private static void write() { | |
E e1 = E.E2; | |
e1.a.t = 51; | |
ObjectOutputStream objectOutputStream = null; | |
try { | |
FileOutputStream fileOutputStream = new FileOutputStream( | |
"storage.txt"); | |
objectOutputStream = new ObjectOutputStream(fileOutputStream); | |
objectOutputStream.writeObject(e1); | |
} catch (IOException e) { | |
} finally { | |
if (objectOutputStream != null) { | |
try { | |
objectOutputStream.close(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment