Octavian Marian
Octavian Marian

Reputation: 65

Java: Generic serialize method

It is possible to make a generic serialize method? In which I can pass any object and serialize it acording to it's class? Something like this:

public void serializeObject(T Object) {

    try (ObjectOutputStream clientOutputStream = new ObjectOutputStream(socketConnection.getOutputStream());) {

        clientOutputStream.writeObject(Object);

        System.out.println(user.getUsername());

        //clientOutputStream.close();

    } catch (Exception e) {
        System.out.println(e);
    }
}

Upvotes: 1

Views: 2357

Answers (3)

Vijayakumar
Vijayakumar

Reputation: 303

It is not possible to create Generic Serializer. Instead you can convert your object to common object that supports serialization.

For example, You can convert your object to String using GSON and serialize the string. During deserialization you pass the deserialized string object to gson to get your object back.

public <T> void serializeObject(T object) throws Exception{
    Gson gson = new Gson();
    String stringToSerialize = gson.toJson(object).toString();
    try(ObjectOutputStream oStream = new ObjectOutputStream(new FileOutputStream("generic.ser"))){
        oStream.writeObject(stringToSerialize);
    }
}

public <T> T deSerializeObject(Class className) throws Exception{
    Gson gson = new Gson();
    try(ObjectInputStream iStream = new ObjectInputStream(new FileInputStream("generic.ser"))){
        String object = (String)iStream.readObject();
        return (T) gson.fromJson(object,className);
    }
}

Ofcourse this solution comes with performance degrade. It completely depends on our requirement.

Upvotes: 0

GhostCat
GhostCat

Reputation: 140573

You could build something like this using reflection. You inspect the object to dump; retrieve all its fields; and then try to serialize those. Of course, that will turn out to be hard, because you have to detect "cycles", to avoid serializing A pointing to B pointing to C pointing back to A for example.

And you would have to understand all the subtle issues, like having inner objects and whatnot. Seriously: this is hard.

Then: serialization isn't the even real problem in this challenge!

The problem is to rebuild objects of generic classes from the serialized data.

So, the real answer is: this is an advanced task where you can easily waste many hours of time. Meaning: you rather step back and clarify your requirements. Instead of re-inventing the wheel, you should use your energy to find an existing framework that matches your needs. Start reading here.

Upvotes: 1

Tomas F.
Tomas F.

Reputation: 720

Try out-of-the-box mappers, e.g. Jackson JSON mapper

import com.fasterxml.jackson.databind.ObjectMapper;

ObjectMapper mapper = new ObjectMapper();
String jsonInString = mapper.writeValueAsString(yourObject);

YourClass yourObject = mapper.readValue(jsonInString, YourClass.class);

Upvotes: 0

Related Questions