avro-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Niels Basjes <Ni...@basjes.nl>
Subject [DISCUSS][JAVA] Generating toBytes/fromBytes methods?
Date Fri, 18 Dec 2015 13:01:59 GMT

I'm working on a project where I'm putting Avro records into Kafka and at
the other end pull them out again.
For that purpose I wrote two methods 'toBytes' and 'fromBytes' in a
separate class (see below).

I see this as the type of problem many developers run into.
Would it be a good idea to generate methods like these into the generated
Java code?

This would make it possible to serialize and deserialize singles records
like this:

byte [] someBytes = measurement.toBytes();
Measurement m = Measurement.fromBytes(someBytes);

Niels Basjes

P.S. possibly not name it toBytes but getBytes (similar to what the String
class has)

public final class MeasurementSerializer {
    private MeasurementSerializer() {

    public static Measurement fromBytes(byte[] bytes) throws IOException {
        try {
            DatumReader<Measurement> reader = new
            Decoder decoder = DecoderFactory.get().binaryDecoder(bytes, null);
            return reader.read(null, decoder);
        } catch (RuntimeException rex) {
            throw new IOException(rex.getMessage());

    public static byte[] toBytes(Measurement measurement) throws IOException {
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            Encoder encoder = EncoderFactory.get().binaryEncoder(out, null);
            SpecificDatumWriter<Measurement> writer = new
            writer.write(measurement, encoder);
            return out.toByteArray();
        } catch (RuntimeException rex) {
            throw new IOException(rex.getMessage());

Best regards / Met vriendelijke groeten,

Niels Basjes

  • Unnamed multipart/alternative (inline, None, 0 bytes)
View raw message