mercredi 30 novembre 2016

Proper way to get a possibly-repeated annotation?

Java 8 introduced repeating annotations, but had to shoehorn them in over the existing structure which didn't directly support them. They did this by introducing a @Repeatable meta-annotation but you get different behavior depending on whether there's one or more-than-one annotation on an object:

If more than one annotation of the requested type is present, you can obtain them by first getting their container annotation.

This implies that if only one annotation is present you can't use the container annotation, and lo-and-behold that appears to be the case. I wrote the following to handle the one and more-than-one cases together, but it seems overly-complex. Is there a cleaner way to go about this? The docs also mention using AnnotatedElement but I don't see how to use this; the methods only seem to take Class objects, not Method or Field objects.

public static <C, T> List<T> getAnnotations(
    Method m, Class<C> containerClass, Class<T> annotationClass) {
  C container = m.getAnnotation(containerClass);
  if (container != null && container.value().length > 0) {
    return ImmutableList.copyOf(container.value());
  }
  // apparently the @Container isn't considered set unless
  // there's *repeated* @Annotation elements
  T annotation = m.getAnnotation(annotationClass);
  if (annotation != null) {
    return ImmutableList.of(annotation);
  }
  return ImmutableList.of();
}





Aucun commentaire:

Enregistrer un commentaire