Kristian Rickert created AVRO-3660:
--------------------------------------

             Summary: SpecificRecord java data generator helper method - should 
I contribute?
                 Key: AVRO-3660
                 URL: https://issues.apache.org/jira/browse/AVRO-3660
             Project: Apache Avro
          Issue Type: Improvement
          Components: java
    Affects Versions: 1.11.1
            Reporter: Kristian Rickert


I'm not sure if this is useful or if there's already something there for Avro - 
but I wrote a simple helper method for Java users that allows for RandomData to 
return a specific data type when given a class.  

So when I'm writing tests for my schema data, I generate the SpecificRecord 
classes by doing this:

Given: generated classes with avro in java.

In this case, imagine there's a generated class called {{Article}}

What this does:
{code:java}
 Article randomArticleData = specificAvroRecordGenerator(Article.class){code}
I'm aware the RandomData class can create GenericData, but I've found this 
method to be very useful when writing code that goes to a queue to test and 
end-to-end transport without having to write too much code.

However, i'm not sure if something is already in the repo that does this.

So here's my implementation:
{code:java}
public static <T extends SpecificRecordBase> T 
specificAvroRecordGenerator(Class<T> avroClassType) {
    try {
        Field field = avroClassType.getDeclaredField("SCHEMA$");
        return specificAvroRecordGenerator((Schema)field.get(null));
    } catch (IllegalAccessException | NoSuchFieldException e) {
        throw new RuntimeException(e);
    }
}

@SuppressWarnings("unchecked")
public static <T extends SpecificRecordBase> T 
specificAvroRecordGenerator(Schema schema) {
        GenericRecord test =
                (GenericRecord)new RandomData(schema, 1)
                        .iterator().next();
        return (T) SpecificData.get().deepCopy(test.getSchema(), test);
}{code}
The good: it works

The bad:  it uses reflection because the current RandomData class outputs 
generic data classes instead.

I don't think that is necessarily bad.  But I think it's a really useful set of 
2 methods.  I saw a couple people on stackoverflow inquire about it.

 

So my two questions: 

1) is there a simple method that already does this and I can't find it?

2) is there an easier way to do this?

I'd be happy to contribute.  Let me know if I should



--
This message was sent by Atlassian Jira
(v8.20.10#820010)

Reply via email to