繁体   English   中英

如何在Java中将对象转换为可序列化

[英]How to convert Object to Serializable in java

这个问题很简单,但是鉴于我还没有发现互联网上的任何东西来做我想实现的目标,因此我认为答案不是这样。 我有两个类:GenericModel和GenericBean。 Thos类包含一个地图,两者都包含。 代码如下:

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;
    }
}

第二:

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>();

}

我要实现的是在Generic bean的map属性中复制GenericModel的map属性。

但是我遇到编译错误,导致Map<String,Object>Map<String,Serializable>不兼容,我该怎么办?

您可以:

  • 迭代“源地图”
  • 对于值是instanceof序列化的每个键/值,请将该键/值对添加到“接收器”映射中
  • 正如许多评论中所述:至少从理论上讲,您需要考虑如何处理未实现该接口的值

如果您决定使用强制转换,则可以为此使用Stream 在这种情况下,所有不可序列化的属性将被忽略:

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}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM