In Java language: Serialization a) Create an Employee class in which you can sto
ID: 3693782 • Letter: I
Question
In Java language:
Serialization
a)
Create an Employee class in which you can store employees’ identification/employee number, first and last names, phone numbers, employee salary, the month and day that each employee was hired. Write an application that can prompt the user to capture employee data and uses serialization to store each employees’ record to a file called (whatever you like).dat.
In order to accomplish the above task, you need to do the following:
Declare six instance variables for the pieces of data about an employee as listed above in (a) i.e. private int employeeNumber
private String firstName
private String lastName, etc.
Create two constructors; one default and the other with parameters.
You are required to provide appropriate getters and setters.
Create an output stream for file (whatever you like).dat to facilitate the writing of an object to a file.
Create an Employee[] array that will help in capturing employee data and writing it to a file as an array object.
Deserialization:
Create a program that reads the file created in Question#1 (a) above displaying each employee’s data to the screen.
Explanation / Answer
package com.EMP.serialization.proxy;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
public class Data implements Serializable{
private static final long serialVersionUID = 2XXXXXXXXXXXXXXXXXXXXX;
private String data;
public Data(String d){
this.data=d;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
@Override
public String toString(){
return "Data{data="+data+"}";
}
//serialization proxy class
private static class DataProxy implements Serializable{
private static final long serialVersionUID = 8XXXXXXXXXXXXXXX;
private String dataProxy;
private static final String PREFIX = "ABC";
private static final String SUFFIX = "DEFG";
public DataProxy(Data d){
//obscuring data for security
this.dataProxy = PREFIX + d.data + SUFFIX;
}
private Object readResolve() throws InvalidObjectException {
if(dataProxy.startsWith(PREFIX) && dataProxy.endsWith(SUFFIX)){
return new Data(dataProxy.substring(3, dataProxy.length() -4));
}else throw new InvalidObjectException("data corrupted");
}
}
//replacing serialized object to DataProxy object
private Object writeReplace(){
return new DataProxy(this);
}
private void readObject(ObjectInputStream ois) throws InvalidObjectException{
throw new InvalidObjectException("Proxy is not used, something fishy");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.