2番目の質問について:生成されたAVRO Javaクラスをラップ/拡張してメソッドを追加するにはどうすればよいですか?
AspectJを使用して、既存の/生成されたクラスに新しいメソッドを挿入できます。AspectJはコンパイル時にのみ必要です。アプローチを以下に示します。
PersonレコードをAvroIDL(person.avdl)として定義します。
@namespace("net.tzolov.avro.extend")
protocol PersonProtocol {
record Person {
string firstName;
string lastName;
}
}
mavenとavro-maven-pluginを使用して、AVDLからJavaソースを生成します。
<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>
上記の構成は、person.avidファイルがsrc / main / resources/avroにあることを前提としています。ソースはtarget/generated-sources/javaで生成されます。
生成されたPerson.javaには、getFirstName()とgetLastName()の2つのメソッドがあります。getCompleteName() = firstName + lastNameという別のメソッドで拡張する場合は、次の側面でこのメソッドを挿入できます。
package net.tzolov.avro.extend;
import net.tzolov.avro.extend.Person;
public aspect PersonAspect {
public String Person.getCompleteName() {
return this.getFirstName() + " " + this.getLastName();
}
}
生成されたコードでこのアスペクトを織り込むには、aspectj-maven-pluginmavenプラグインを使用します
<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>
そして結果:
@Test
public void testPersonCompleteName() throws Exception {
Person person = Person.newBuilder()
.setFirstName("John").setLastName("Atanasoff").build();
Assert.assertEquals("John Atanasoff", person.getCompleteName());
}