softwareplay
softwareplay

Reputation: 1409

How to convert Object to Serializable in java

this question is very simple but i don't think that the answer is as such given that i haven't found anything around the internet to do what i want to achieve. I have two classes: GenericModel and GenericBean. Thos classes contains a map, Both of them. The code is the following:

public class GenericBean implements IsSerializable {
    Map<String, Serializable> properties = new HashMap<String, Serializable>();

    public Object getProperty(String key){

        return properties.get(key);
    }

    public void setProperty(String key, Serializable value){
        properties.put(key, value);
    }

    public Map<String, Serializable> getProperties() {
        return properties;
    }

    public void setProperties(Map<String, Serializable> properties) {
        this.properties = properties;
    }
}

The second:

public class GenericModel {
private final Logger log = LoggerFactory.getLogger(GenericModel.class);

public Map<String, Object> getProperties() {
    return properties;
}

public Object getProperty(String key) {
    return properties.get(key);
}

public void setProperty(String key, Object value) {
    properties.put(key, value);
}

public void setProperties(Map<String, Object> properties) {
    this.properties = properties;
}

private Map<String, Object> properties = new HashMap<String, Object>();

}

What i want to achieve is to copy the map Properties of GenericModel in the map Properties of Generic bean.

But i get a compilation error, cause the Map<String,Object> is not compatible with the Map<String,Serializable> What should i do?

Upvotes: 3

Views: 6777

Answers (2)

Anton Balaniuc
Anton Balaniuc

Reputation: 11739

If you will decide to use casting, you might use Stream for this. All non-serializable properties will be ignored in this case:

Map<String, Object> properties = new HashMap<>();
properties.put("ser", "String");
properties.put("non ser", new Object());

Map<String, Serializable> serializableMap = properties.entrySet().stream()
        .filter(entry -> entry.getValue() instanceof Serializable)
        .collect(Collectors.toMap(Map.Entry::getKey, e -> (Serializable) e.getValue()));

System.out.println(serializableMap); //{ser=String}

Upvotes: 2

GhostCat
GhostCat

Reputation: 140613

You can:

  • iterate the "source map"
  • for each key/value where the value is instanceof Serializable - you add that key/value pair to the "sink" map
  • and as mentioned in the many comments: at least theoretically you need to think up what to do about values that do not implement that interface

Upvotes: 2

Related Questions