opwvhk commented on code in PR #3425:
URL: https://github.com/apache/avro/pull/3425#discussion_r2215987091
##########
lang/java/avro/src/main/java/org/apache/avro/reflect/ReflectData.java:
##########
@@ -1042,4 +1045,36 @@ public Object newRecord(Object old, Schema schema) {
}
return super.newRecord(old, schema);
}
+
+ public CustomEncoding getCustomEncoding(Schema schema) {
+
+ return this.encoderCache.computeIfAbsent(schema,
this::populateEncoderCache).get();
+ }
+
+ private CustomEncodingWrapper populateEncoderCache(Schema schema) {
+ var enc = ReflectionUtil.getAvroEncode(getClass(schema));
+ if (enc != null) {
+ try {
+ return new
CustomEncodingWrapper(enc.using().getDeclaredConstructor().newInstance());
+ } catch (Exception e) {
+ throw new AvroRuntimeException("Could not instantiate custom
Encoding");
+ }
+ }
+ return new CustomEncodingWrapper(null);
+ }
+
+ private class CustomEncodingWrapper {
+
+ private final CustomEncoding customEncoding;
+
+ private CustomEncodingWrapper(CustomEncoding customEncoding) {
+ this.customEncoding = customEncoding;
+ }
+
+ public CustomEncoding get() {
+ return customEncoding;
+ }
+
+ }
+
Review Comment:
I like this implementation! As you already mentioned in the PR, it's also
suited for one of the superclasses. However, as the current use case for
`CustomEncoding` is only from `@AvroEncode`, I think it's good as it is now.
##########
lang/java/avro/src/main/java/org/apache/avro/reflect/AvroEncode.java:
##########
@@ -30,7 +30,7 @@
* file. Use of {@link org.apache.avro.io.ValidatingEncoder} is recommended.
*/
@Retention(RetentionPolicy.RUNTIME)
-@Target(ElementType.FIELD)
+@Target({ ElementType.FIELD, ElementType.TYPE })
Review Comment:
Please add `@Inherited` as well (see my comment on the class
`ReflectionUtil`).
##########
lang/java/avro/src/main/java/org/apache/avro/reflect/ReflectionUtil.java:
##########
@@ -188,4 +189,28 @@ public static <V, R> Function<V, R>
getConstructorAsFunction(Class<V> parameterC
}
}
+ protected static AvroEncode getAvroEncode(Field field) {
+ var enc = field.getAnnotation(AvroEncode.class);
+ if (enc != null) {
+ return enc;
+ } else {
+ return getAvroEncode(field.getType());
+ }
+ }
+
+ protected static AvroEncode getAvroEncode(Class<?> clazz) {
+ if (clazz == null) {
+ return null;
+ }
+ AvroEncode enc = clazz.getAnnotation(AvroEncode.class);
+ if (enc != null) {
+ return enc;
+ }
+ // try superclasses
+ Class<?> superclass = clazz.getSuperclass();
+ if (superclass != null && superclass != Object.class) {
+ return getAvroEncode(superclass);
+ }
Review Comment:
This is not needed if the annotation is `@Inherited`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]