Created
September 23, 2015 06:48
-
-
Save tasukujp/4b9154934a0b4928415b to your computer and use it in GitHub Desktop.
Serializable
This file contains hidden or 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
| import java.io.Serializable; | |
| public class Person implements Serializable { | |
| private String firstName; | |
| private String lastName; | |
| private int age; | |
| public Person(String firstName, String lastName, int age) { | |
| this.firstName = firstName; | |
| this.lastName = lastName; | |
| this.age = age; | |
| } | |
| public String getFirstName() { | |
| return firstName; | |
| } | |
| public void setFirstName(String firstName) { | |
| this.firstName = firstName; | |
| } | |
| public String getLastName() { | |
| return lastName; | |
| } | |
| public void setLastName(String lastName) { | |
| this.lastName = lastName; | |
| } | |
| public int getAge() { | |
| return age; | |
| } | |
| public void setAge(int age) { | |
| this.age = age; | |
| } | |
| } |
This file contains hidden or 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
| import org.junit.Test; | |
| import java.io.*; | |
| import static org.hamcrest.core.Is.is; | |
| import static org.junit.Assert.assertThat; | |
| import static org.junit.Assert.fail; | |
| public class SerializableSampleTest { | |
| @Test | |
| public void serializableSample() { | |
| // シリアライズ | |
| try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.txt"))) { | |
| Person person = new Person("John", "Williams", 55); | |
| oos.writeObject(person); | |
| } catch (IOException e) { | |
| fail(e.getMessage()); | |
| } | |
| // デシリアライズ | |
| try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.txt"))) { | |
| Person dePerson = (Person) ois.readObject(); | |
| assertThat(dePerson.getFirstName(), is("John")); | |
| assertThat(dePerson.getLastName(), is("Williams")); | |
| assertThat(dePerson.getAge(), is(55)); | |
| } catch (IOException | ClassNotFoundException e) { | |
| fail(e.getMessage()); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment