I decorated an ObjectMapper
and provided an additional abstraction layer to avoid coupling with ObjectMapper
directly. Take a look:
class ClientServerCommunicator {
private static final Serializer serializer = new JacksonSerializer();
// more code
public interface Serializer {
String serialize(Object object);
<T> T deserialize(String serializedObject, Class<T> clazz);
}
public class JacksonSerializer implements Serializer {
private final ObjectMapper objectMapper = new ObjectMapper();
@Override
@SneakyThrows
public String serialize(Object object) {
return objectMapper.writeValueAsString(object);
}
@Override
@SneakyThrows
public <T> T deserialize(String serializedObject, Class<T> clazz) {
return objectMapper.readValue(serializedObject, clazz);
}
@SneakyThrows
// not present in the interface!
public <T> T deserialize(String serializedObject, TypeReference<T> typeReference) {
return objectMapper.readValue(serializedObject, typeReference);
}
}
However, when it comes to deserialization of generic types, I'm not sure how I should describe it in my interface. So far, I simply cast to JacksonSerializer
which will fail if I decide to use another implementation
ServerSocketMessage<ChatAuthentication> serverResponse = ((JacksonSerializer) serializer).deserialize(line, new TypeReference<>() {
});
Should I add an additional abstraction layer for TypedReference
? What if other libraries handle it differently (they don't pass some generic dummy)?
What would you recommend?
Aucun commentaire:
Enregistrer un commentaire