code: public long byteCount(Object object) {
          try {
              CountingOutputStream cos = new CountingOutputStream(new OutputStream() {
                  @Override
                  public void write(int b) throws IOException {
                      // do nothing
                  }
              });
              ObjectOutputStream os = new ObjectOutputStream(cos);
  
              os.writeObject(object);
              os.flush();
              os.close();
              return cos.getCount();
          } catch (IOException e) {
              throw new IllegalStateException("error serializing object: " + e.getMessage(),e);
          }
      }
docs: Calculate the serialized object size in bytes. This is a good indication of how much memory the object roughly takes.
  Note that this is typically not exactly the same for many objects.
  @param object any  object that implements {@link Serializable}
  @return number of bytes of the serialized object.