Regarding the second question: How can I wrap / extend the created Java classes to add methods?
You can use AspectJ to introduce new methods to an existing / generated class. AspectJ is only required at compile time. The approach is shown below.
Define the Person entry as Avro IDL (person.avdl):
@namespace("net.tzolov.avro.extend") protocol PersonProtocol { record Person { string firstName; string lastName; } }
use maven and avro-maven-plugin to generate java sources from AVDL:
<dependency> <groupId>org.apache.avro</groupId> <artifactId>avro</artifactId> <version>1.6.3</version> </dependency> ...... <plugin> <groupId>org.apache.avro</groupId> <artifactId>avro-maven-plugin</artifactId> <version>1.6.3</version> <executions> <execution> <id>generate-avro-sources</id> <phase>generate-sources</phase> <goals> <goal>idl-protocol</goal> </goals> <configuration> <sourceDirectory>src/main/resources/avro</sourceDirectory> <outputDirectory>${project.build.directory}/generated-sources/java</outputDirectory> </configuration> </execution> </executions> </plugin>
Above the configuration, it is assumed that the person.avid file is located in src / main / resources / avro. Sources are generated in target / generated sources / java.
The generated Person.java has two methods: getFirstName () and getLastName (). If you want to expand it in another way: getCompleteName () = firstName + lastName, you can introduce this method with the following aspect:
package net.tzolov.avro.extend; import net.tzolov.avro.extend.Person; public aspect PersonAspect { public String Person.getCompleteName() { return this.getFirstName() + " " + this.getLastName(); } }
Use aspectj-maven-plugin maven plugin to weave this aspect with generated code
<dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.6.12</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.6.12</version> </dependency> .... <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>aspectj-maven-plugin</artifactId> <version>1.2</version> <dependencies> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.6.12</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjtools</artifactId> <version>1.6.12</version> </dependency> </dependencies> <executions> <execution> <goals> <goal>compile</goal> <goal>test-compile</goal> </goals> </execution> </executions> <configuration> <source>6</source> <target>6</target> </configuration> </plugin>
and the result:
@Test public void testPersonCompleteName() throws Exception { Person person = Person.newBuilder() .setFirstName("John").setLastName("Atanasoff").build(); Assert.assertEquals("John Atanasoff", person.getCompleteName()); }
source share