DarVar
DarVar

Reputation: 18144

Create a SpecificRecord from an Avro Schema programmatically

I'm working with the following code that takes a org.apache.avro.Schema and returns a org.apache.avro.generic.GenericRecord.

How can I change it to return a org.apache.avro.specific.SpecificRecord instead?

  private GenericRecord generateRecord(Schema schema) {
    GenericRecordBuilder builder = new GenericRecordBuilder(schema);
    for (Schema.Field field : schema.getFields()) {
      builder.set(field, generateObject(field.schema()));
    }
    return builder.build();
  }

e.g.

if (schema.getName().equals("MyCustomRecord")) {
    // code to create SpecificRecord here from Schema
}

Upvotes: 1

Views: 558

Answers (1)

vortal
vortal

Reputation: 21

you can create a new instance by SpecificData and cast it for class you need

(T) SpecificData.newInstance(event.getClass(), event.getSchema());

Next method for example:

    @SuppressWarnings("unchecked")
private <T extends SpecificRecordBase, D extends SpecificRecordBase> T getStructedEvent(T event, D dEvent) {
    T result = (T) SpecificData.newInstance(event.getClass(), event.getSchema());
    dEvent.getSchema().getFields().forEach(field -> {
        result.put(field.name(), dEvent.get(field.name()));
    });
    return result;
}

Upvotes: 0

Related Questions