javaserializationavrojsonschema

Generate Avro Schema from certain Java Object


Apache Avro provides a compact, fast, binary data format, rich data structure for serialization. However, it requires user to define a schema (in JSON) for object which need to be serialized.

In some case, this can not be possible (e.g: the class of that Java object has some members whose types are external java classes in external libraries). Hence, I wonder there is a tool can get the information from object's .class file and generate the Avro schema for that object (like Gson use object's .class information to convert certain object to JSON string).


Solution

  • Take a look at the Java reflection API.

    Getting a schema looks like:

    Schema schema = ReflectData.get().getSchema(T);
    

    See the example from Doug on another question for a working example.

    Credits of this answer belong to Sean Busby.