-
-
Save AndreKoepke/38a154a252a1cca0faf9ba48b21c8e3a to your computer and use it in GitHub Desktop.
Bad java code ...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// we all know the ObjectMapper from Jackson | |
// pretty cool - but it has an annoying checked exception | |
// many people build a wrapper to make it unchecked | |
// | |
// I'm working on a project and found this: | |
public interface Serializer { | |
<T> byte[] serialize(T obj, Class<T> clazz); | |
<T> void serialize(T obj, OutputStream outputStream, Class<T> clazz); | |
<T> T deserialize(byte[] payload, Class<T> clazz); | |
<T> T deserialize(InputStream inputStream, Class<T> clazz); | |
} | |
// not enough, they using lomboks "@SneakyThrows" annotation, which is making this wrapper more pointless | |
@Component | |
@RequiredArgsConstructor | |
public class PlainJsonSerializer implements Serializer { | |
private final ObjectMapper objectMapper; | |
@Override | |
@SneakyThrows | |
public <T> byte[] serialize(T obj, Class<T> clazz) { | |
return objectMapper.writeValueAsBytes(obj); | |
} | |
@Override | |
@SneakyThrows | |
public <T> void serialize(T obj, OutputStream outputStream, Class<T> clazz) { | |
outputStream.write(serialize(obj, clazz)); | |
} | |
@Override | |
@SneakyThrows | |
public <T> T deserialize(byte[] payload, Class<T> clazz) { | |
return objectMapper.readValue(payload, clazz); | |
} | |
@Override | |
@SneakyThrows | |
public <T> T deserialize(InputStream inputStream, Class<T> clazz) { | |
return objectMapper.readValue(inputStream, clazz); | |
} | |
} | |
// but they don't stop | |
// they also wrote a test-class for it | |
// wtf ... | |
public class SerializerTest { | |
@Test | |
void testJson() { | |
var data = test(new PlainJsonSerializer(new JacksonConfig().objectMapper())); | |
assertThat(data).isEqualTo("{\"data\":123}".getBytes()); | |
} | |
private byte[] test(Serializer serializer) { | |
var data = new Data(123) | |
var serializedData = serializer.serialize(data, Data.class); | |
var data_ = serializer.deserialize(serializedData, Data.class); | |
assertThat(data).isEqualTo(data_); | |
return data; | |
} | |
} | |
// | |
// if oyu ever thinking about to do this ... you can simplify this to the following: | |
// | |
@RequiredArgsConstructor | |
class YourClass { | |
private final ObjectMapper objectMapper; | |
@SneakyThrows | |
void yourMethod() { | |
objectMapper.serialize(yourObject); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment