Skip to content

Commit

Permalink
feat: add utitlity for support serialization of nullable value
Browse files Browse the repository at this point in the history
  • Loading branch information
bsorrentino committed Aug 9, 2024
1 parent 9776cbd commit 7a82029
Showing 1 changed file with 16 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,28 @@

import java.io.*;
import java.util.Objects;
import java.util.Optional;

public interface Serializer<T> {

void write(T object, ObjectOutput out) throws IOException;


T read(ObjectInput in) throws IOException, ClassNotFoundException ;

default void writeNullable(T object, ObjectOutput out) throws IOException {
if( object == null ) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
write(object, out);
}
}
default Optional<T> readNullable(ObjectInput in) throws IOException, ClassNotFoundException {
if( in.readBoolean() ) {
return Optional.ofNullable(read(in));
}
return Optional.empty();
}

default byte[] writeObject(T object) throws IOException {
Objects.requireNonNull( object, "object cannot be null" );
try( ByteArrayOutputStream baos = new ByteArrayOutputStream() ) {
Expand Down

0 comments on commit 7a82029

Please sign in to comment.