如何在java

时间:2017-09-08 15:45:26

标签: java serialization

这个问题非常简单,但我不认为答案是这样的,因为我没有在互联网上找到任何可以实现我想要的东西。我有两个类: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中复制GenericModel的地图属性。

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

2 个答案:

答案 0 :(得分:2)

你可以:

  • 迭代“源地图”
  • 对于值为instanceof的每个键/值,可序列化 - 您将该键/值对添加到“接收器”地图
  • 并且如许多评论中所述:至少在理论上你需要考虑如何处理未实现该接口的值

答案 1 :(得分:1)

如果您决定使用强制转换,则可以使用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}