HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Serialization/Deserialization with Generics in Java

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
withserializationjavadeserializationgenerics

Problem

I've Implemented a Serialization Utility which Serializes/DeSerializes a class, along with writing JUnit Test Cases for the same.

Please Review the code and Suggest me how to improve it. Particularly in generics as I've not written much code with Generics in java.

SerializableEmployee.java - Class to be Serialized

public class SerializableEmployee implements Serializable{

    /**
     * This Serial version UID will change once any new version of class has been created
     */
    private static final long serialVersionUID = 1L;

    private String name;

    public SerializableEmployee(String name) {
        this.name = name;
    }

    public String getName(){
        return name;
    }

    @Override
    public String toString() {
        return "SerializableEmployee{" +
                "name='" + name + '\'' +
                '}';
    }
}


SerializationUtil.java - Util for Serializing and Deserializing

```
/**
* Created by shashi on 21/12/15.
*
* @param Type of class to Serialize and Deserialize from
*/
public class SerializationUtil {

/**
* Logger for the class
*/
public Logger LOG = LoggerFactory.getLogger("WHAT to Write here instead of T.class");

/**
* Serializes the given {@link T} object and save it into a file
* @param type {@link T} object to be Serialized
* @param fileName File in which {@link T} object is to be saved
*
* @return boolean specifying if {@link T} object has been serialized
*/
public boolean serialize(T type, String fileName) {

try(FileOutputStream fileStream = new FileOutputStream(fileName);
ObjectOutputStream objectStream = new ObjectOutputStream(fileStream)) {
objectStream.writeObject(type);
}catch(IOException inputOutputException){
LOG.error("Exception Occurred while Serializing {}. Message is ", "WHAT to Write here instead of T.class", inputOutputException.getMessage());

return false;

Solution

-
SerializationUtil should work on T extends Serializable instead of T. This makes misuse harder.

-
Prefixing serializable to a data-holder is unnecessary for almost all intents and purposes.

-
You may be interested in operating on Path instead of String when Serializing and deSerializing

-
Your Util does not provide a way to serialize multiple instances of the same class :/

Context

StackExchange Code Review Q#114629, answer score: 4

Revisions (0)

No revisions yet.