Avro Reflect API example

We have seen here, that Avro supports three kinds of API (Generic,Specific,reflect). In this blog we will see how to use Reflect API. Reflect API is use full when you already have your java classes defined. For generic API example see this blog.

The advantage of the relfect api is that , you don’t have to define a schema, you can simply generate a schema from the existing type. For example you have a studnet class, you can generate a schema usign the follwing code


Schema schema=ReflectData.get().getSchema(Student.class);

You need to use the ReflectDatumWriter to get a writer , you can pass schema or the class to the constructor of the writer. Once you have the writer , writing the data to the file (marshaling or serializing) is same as with the Generic API.

Avro Reflect API Example

lets say we have a class Person , and we want to serialize and then deserializing this class.

Schema schema=ReflectData.get().getSchema(Person.class);
 DatumWriter<Person> writer=new ReflectDatumWriter<Person>(schema);
 ByteArrayOutputStream out=new ByteArrayOutputStream();
 Encoder encoder=EncoderFactory.get().binaryEncoder(out, null);
 Person p=new Person("Anshu","Parida");
 writer.write(p,encoder);
 encoder.flush();
 System.out.println("Serilization complete");
 
 DatumReader<Person> reader=new ReflectDatumReader<Person>(schema);
 Decoder decoder=DecoderFactory.get().binaryDecoder(out.toByteArray(), null);
 Person dep=reader.read(null, decoder);
 System.out.println("Deserilzation complete");
 System.out.println("Before serlization "+p);
 System.out.println("After deserilization "+p);

full project is available on github

 

Add a Comment

Your email address will not be published. Required fields are marked *