Get class from schema programmatically (Apache avro)

13,146

Avro does not generate the Java types at runtime. You will either have to write and populate it manually, use a generic Schema instance or compile the schema definition to a Java class using Avro Tools or the Avro Maven plugin. You probably don't want to do the first one.

1. Use a generic Schema representation

If you want to simply create a record that contains your schema data which enforces the schema, you can use GenericRecord:

GenericRecord datum = new GenericData.Record(schema);
datum.put("field1", fieldValue)`

This will throw an AvroRuntimeException if field1 is not defined in your schema.

2. Generating a Java class

If you have a schema that describes a Fish, and you would like to have a corresponding Java com.example.Fish, you will need to compile it from your schema. You can do this with Avro Tools or the Avro Maven plugin, see the documentation. Note that the "namespace" property determines the package hierarchy of the class.

Now that you have the corresponding Java class, there are a couple of different ways to populate it with data.

Share:
13,146
Leem.fin
Author by

Leem.fin

A newbie in software development.

Updated on June 13, 2022

Comments

  • Leem.fin
    Leem.fin almost 2 years

    I am using Apache Avro.

    I defined the schema json string in my java code:

    String schemaStr = STRING_IN_JSON_FORMAT;
    
    //use Parser to parse above string to Schema object
    Schema.Parser parser = new Schema.Parser(); 
    Schema schema = parser.parse(schemaStr);
    //How to programmatically get the class from the schema I got at this point?
    

    How to continue my code to get the class from the schema programmatically?