001package serialization;
002import java.io.*;
003
004public class Main2 {
005        public static void main(String args[]) {
006                try {
007                        Person person = new Person("Matt", 30);
008                        PersonEntry entry = new PersonEntry(person, 1);
009                        ObjectOutputStream os
010                        = new ObjectOutputStream (new FileOutputStream("out.dat"));
011                        os.writeObject(entry);
012                        os.close();
013
014                        ObjectInputStream is
015                        = new ObjectInputStream (new FileInputStream("out.dat"));
016                        Object o = is.readObject();
017                        is.close();
018
019                        PersonEntry entry2 = (PersonEntry) o;
020                        System.out.println("Entry restored from file is" + entry2.toString());
021                } catch (Exception e) { e.printStackTrace(); }
022        }
023}
024
025class PersonEntry implements Serializable {
026        private static final long serialVersionUID = 2008L;
027        private Person person = null;
028        private int personNumber = 0;
029
030        public PersonEntry(Person person, int personNumber) {
031                this.person = person;
032                this.personNumber = personNumber;
033        }
034        public Person getPerson() {
035                return person;
036        }
037        public int getPersonNumber() {
038                return personNumber;
039        }
040        public String toString() {
041                return person.toString() +  " Number " + Integer.toString(personNumber);
042        }
043}
044
045@SuppressWarnings("serial")
046class Person implements Serializable {
047        private String name = "";
048        private int age = 0;
049
050        public Person(String name, int age) {
051                this.name = name;
052                this.age = age;
053        }
054        public String getName() {
055                return name;
056        }
057        public int getAge() {
058                return age;
059        }
060        public String toString() {
061                return "Name: " + name + " Age: " + Integer.toString(age);
062        }
063}
064