Serialisation
To send a class file over internet, load the class into a txt file and decrypt it later. Or to save state of a class.
For example
@Test
public void userShouldBeSerialisable() throws IOException, NoSuchFieldException, IllegalAccessException, ClassNotFoundException {
User user = new User();
File serialiseFile = new File("user_serialise");
// Step 1: serialise into a text file
FileOutputStream fileOutputStream = new FileOutputStream(serialiseFile);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(user);
objectOutputStream.flush();
objectOutputStream.close();
// Step 2: read through that text file and convert back to a class
FileInputStream fileInputStream = new FileInputStream(serialiseFile);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
User receivedUser = (User) objectInputStream.readObject();
// Step 3: Get and compare serialVersionUID
Long userSerialVersionUID= (Long) user.getClass().getDeclaredField("serialVersionUID").get(user);
Long receivedSerialVersionUID= (Long) receivedUser.getClass().getDeclaredField("serialVersionUID").get(receivedUser);
assertEquals(userSerialVersionUID, receivedSerialVersionUID);
// Step 4: Clean up
objectOutputStream.close();
serialiseFile.delete();
}
Given the User
class
public class User implements Serializable {
public static final long serialVersionUID = 1L;
private String userId;
private Browser browser;
private String getUserId() {
return userId;
}
private void setUserId(String id) {
userId = id;
}
public Browser getBrowser() {
return browser;
}
public void setBrowser(Browser browser) {
this.browser = browser;
}
}
Note: Browser class needs to be also serializable
public class Browser implements Serializable {
private String name;
private String version;
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
For field that you don't need, we use transient
to mark that the field is not being serialised
class Person {
private transient int age;
}