1 /*
   2  * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.lang.reflect;
  27 
  28 import java.lang.annotation.Annotation;
  29 import java.lang.annotation.AnnotationFormatError;
  30 import java.lang.annotation.Repeatable;
  31 import java.util.Arrays;
  32 import java.util.LinkedHashMap;
  33 import java.util.Map;
  34 import java.util.Objects;
  35 import java.util.function.Function;
  36 import java.util.stream.Collectors;
  37 import sun.reflect.annotation.AnnotationSupport;
  38 import sun.reflect.annotation.AnnotationType;
  39 
  40 /**
  41  * Represents an annotated element of the program currently running in this
  42  * VM.  This interface allows annotations to be read reflectively.  All
  43  * annotations returned by methods in this interface are immutable and
  44  * serializable. The arrays returned by methods of this interface may be modified
  45  * by callers without affecting the arrays returned to other callers.
  46  *
  47  * <p>The {@link #getAnnotationsByType(Class)} and {@link
  48  * #getDeclaredAnnotationsByType(Class)} methods support multiple
  49  * annotations of the same type on an element. If the argument to
  50  * either method is a repeatable annotation type (JLS 9.6), then the
  51  * method will "look through" a container annotation (JLS 9.7), if
  52  * present, and return any annotations inside the container. Container
  53  * annotations may be generated at compile-time to wrap multiple
  54  * annotations of the argument type.
  55  *
  56  * <p>The terms <em>directly present</em>, <em>indirectly present</em>,
  57  * <em>present</em>, and <em>associated</em> are used throughout this
  58  * interface to describe precisely which annotations are returned by
  59  * methods:
  60  *
  61  * <ul>
  62  *
  63  * <li> An annotation <i>A</i> is <em>directly present</em> on an
  64  * element <i>E</i> if <i>E</i> has a {@code
  65  * RuntimeVisibleAnnotations} or {@code
  66  * RuntimeVisibleParameterAnnotations} or {@code
  67  * RuntimeVisibleTypeAnnotations} attribute, and the attribute
  68  * contains <i>A</i>.
  69  *
  70  * <li>An annotation <i>A</i> is <em>indirectly present</em> on an
  71  * element <i>E</i> if <i>E</i> has a {@code RuntimeVisibleAnnotations} or
  72  * {@code RuntimeVisibleParameterAnnotations} or {@code RuntimeVisibleTypeAnnotations}
  73  * attribute, and <i>A</i> 's type is repeatable, and the attribute contains
  74  * exactly one annotation whose value element contains <i>A</i> and whose
  75  * type is the containing annotation type of <i>A</i> 's type.
  76  *
  77  * <li>An annotation <i>A</i> is <em>present</em> on an element <i>E</i> if either:
  78  *
  79  * <ul>
  80  *
  81  * <li><i>A</i> is directly present on <i>E</i>; or
  82  *
  83  * <li>No annotation of <i>A</i> 's type is directly present on
  84  * <i>E</i>, and <i>E</i> is a class, and <i>A</i> 's type is
  85  * inheritable, and <i>A</i> is present on the superclass of <i>E</i>.
  86  *
  87  * </ul>
  88  *
  89  * <li>An annotation <i>A</i> is <em>associated</em> with an element <i>E</i>
  90  * if either:
  91  *
  92  * <ul>
  93  *
  94  * <li><i>A</i> is directly or indirectly present on <i>E</i>; or
  95  *
  96  * <li>No annotation of <i>A</i> 's type is directly or indirectly
  97  * present on <i>E</i>, and <i>E</i> is a class, and <i>A</i>'s type
  98  * is inheritable, and <i>A</i> is associated with the superclass of
  99  * <i>E</i>.
 100  *
 101  * </ul>
 102  *
 103  * </ul>
 104  *
 105  * <p>The table below summarizes which kind of annotation presence
 106  * different methods in this interface examine.
 107  *
 108  * <table class="plain">
 109  * <caption>Overview of kind of presence detected by different AnnotatedElement methods</caption>
 110  * <thead>
 111  * <tr><th colspan=2 scope="col">Method</th>
 112  *     <th colspan=4 scope="col">Kind of Presence</th>
 113  * <tr><th scope="col">Return Type</th>
 114  *     <th scope="col">Signature</th>
 115  *     <th scope="col">Directly Present</th>
 116  *     <th scope="col">Indirectly Present</th>
 117  *     <th scope="col">Present</th>
 118  *     <th scope="col">Associated</th>
 119  * </thead>
 120  * <tbody>
 121  * <tr><td style="text-align:right">{@code T}</td>
 122  * <th scope="row" style="font-weight:normal; text-align:left">{@link #getAnnotation(Class) getAnnotation(Class&lt;T&gt;)}
 123  * <td></td><td></td><td style="text-align:center">X</td><td></td>
 124  * </tr>
 125  * <tr><td style="text-align:right">{@code Annotation[]}</td>
 126  * <th scope="row" style="font-weight:normal; text-align:left">{@link #getAnnotations getAnnotations()}
 127  * <td></td><td></td><td style="text-align:center">X</td><td></td>
 128  * </tr>
 129  * <tr><td style="text-align:right">{@code T[]}</td>
 130  * <th scope="row" style="font-weight:normal; text-align:left">{@link #getAnnotationsByType(Class) getAnnotationsByType(Class&lt;T&gt;)}
 131  * <td></td><td></td><td></td><td style="text-align:center">X</td>
 132  * </tr>
 133  * <tr><td style="text-align:right">{@code T}</td>
 134  * <th scope="row" style="font-weight:normal; text-align:left">{@link #getDeclaredAnnotation(Class) getDeclaredAnnotation(Class&lt;T&gt;)}
 135  * <td style="text-align:center">X</td><td></td><td></td><td></td>
 136  * </tr>
 137  * <tr><td style="text-align:right">{@code Annotation[]}</td>
 138  * <th scope="row" style="font-weight:normal; text-align:left">{@link #getDeclaredAnnotations getDeclaredAnnotations()}
 139  * <td style="text-align:center">X</td><td></td><td></td><td></td>
 140  * </tr>
 141  * <tr><td style="text-align:right">{@code T[]}</td>
 142  * <th scope="row" style="font-weight:normal; text-align:left">{@link #getDeclaredAnnotationsByType(Class) getDeclaredAnnotationsByType(Class&lt;T&gt;)}
 143  * <td style="text-align:center">X</td><td style="text-align:center">X</td><td></td><td></td>
 144  * </tr>
 145  * </tbody>
 146  * </table>
 147  *
 148  * <p>For an invocation of {@code get[Declared]AnnotationsByType(Class <T>)},
 149  * the order of annotations which are directly or indirectly
 150  * present on an element <i>E</i> is computed as if indirectly present
 151  * annotations on <i>E</i> are directly present on <i>E</i> in place
 152  * of their container annotation, in the order in which they appear in
 153  * the value element of the container annotation.
 154  *
 155  * <p>There are several compatibility concerns to keep in mind if an
 156  * annotation type <i>T</i> is originally <em>not</em> repeatable and
 157  * later modified to be repeatable.
 158  *
 159  * The containing annotation type for <i>T</i> is <i>TC</i>.
 160  *
 161  * <ul>
 162  *
 163  * <li>Modifying <i>T</i> to be repeatable is source and binary
 164  * compatible with existing uses of <i>T</i> and with existing uses
 165  * of <i>TC</i>.
 166  *
 167  * That is, for source compatibility, source code with annotations of
 168  * type <i>T</i> or of type <i>TC</i> will still compile. For binary
 169  * compatibility, class files with annotations of type <i>T</i> or of
 170  * type <i>TC</i> (or with other kinds of uses of type <i>T</i> or of
 171  * type <i>TC</i>) will link against the modified version of <i>T</i>
 172  * if they linked against the earlier version.
 173  *
 174  * (An annotation type <i>TC</i> may informally serve as an acting
 175  * containing annotation type before <i>T</i> is modified to be
 176  * formally repeatable. Alternatively, when <i>T</i> is made
 177  * repeatable, <i>TC</i> can be introduced as a new type.)
 178  *
 179  * <li>If an annotation type <i>TC</i> is present on an element, and
 180  * <i>T</i> is modified to be repeatable with <i>TC</i> as its
 181  * containing annotation type then:
 182  *
 183  * <ul>
 184  *
 185  * <li>The change to <i>T</i> is behaviorally compatible with respect
 186  * to the {@code get[Declared]Annotation(Class<T>)} (called with an
 187  * argument of <i>T</i> or <i>TC</i>) and {@code
 188  * get[Declared]Annotations()} methods because the results of the
 189  * methods will not change due to <i>TC</i> becoming the containing
 190  * annotation type for <i>T</i>.
 191  *
 192  * <li>The change to <i>T</i> changes the results of the {@code
 193  * get[Declared]AnnotationsByType(Class<T>)} methods called with an
 194  * argument of <i>T</i>, because those methods will now recognize an
 195  * annotation of type <i>TC</i> as a container annotation for <i>T</i>
 196  * and will "look through" it to expose annotations of type <i>T</i>.
 197  *
 198  * </ul>
 199  *
 200  * <li>If an annotation of type <i>T</i> is present on an
 201  * element and <i>T</i> is made repeatable and more annotations of
 202  * type <i>T</i> are added to the element:
 203  *
 204  * <ul>
 205  *
 206  * <li> The addition of the annotations of type <i>T</i> is both
 207  * source compatible and binary compatible.
 208  *
 209  * <li>The addition of the annotations of type <i>T</i> changes the results
 210  * of the {@code get[Declared]Annotation(Class<T>)} methods and {@code
 211  * get[Declared]Annotations()} methods, because those methods will now
 212  * only see a container annotation on the element and not see an
 213  * annotation of type <i>T</i>.
 214  *
 215  * <li>The addition of the annotations of type <i>T</i> changes the
 216  * results of the {@code get[Declared]AnnotationsByType(Class<T>)}
 217  * methods, because their results will expose the additional
 218  * annotations of type <i>T</i> whereas previously they exposed only a
 219  * single annotation of type <i>T</i>.
 220  *
 221  * </ul>
 222  *
 223  * </ul>
 224  *
 225  * <p>If an annotation returned by a method in this interface contains
 226  * (directly or indirectly) a {@link Class}-valued member referring to
 227  * a class that is not accessible in this VM, attempting to read the class
 228  * by calling the relevant Class-returning method on the returned annotation
 229  * will result in a {@link TypeNotPresentException}.
 230  *
 231  * <p>Similarly, attempting to read an enum-valued member will result in
 232  * a {@link EnumConstantNotPresentException} if the enum constant in the
 233  * annotation is no longer present in the enum type.
 234  *
 235  * <p>If an annotation type <i>T</i> is (meta-)annotated with an
 236  * {@code @Repeatable} annotation whose value element indicates a type
 237  * <i>TC</i>, but <i>TC</i> does not declare a {@code value()} method
 238  * with a return type of <i>T</i>{@code []}, then an exception of type
 239  * {@link java.lang.annotation.AnnotationFormatError} is thrown.
 240  *
 241  * <p>Finally, attempting to read a member whose definition has evolved
 242  * incompatibly will result in a {@link
 243  * java.lang.annotation.AnnotationTypeMismatchException} or an
 244  * {@link java.lang.annotation.IncompleteAnnotationException}.
 245  *
 246  * @see java.lang.EnumConstantNotPresentException
 247  * @see java.lang.TypeNotPresentException
 248  * @see AnnotationFormatError
 249  * @see java.lang.annotation.AnnotationTypeMismatchException
 250  * @see java.lang.annotation.IncompleteAnnotationException
 251  * @since 1.5
 252  * @author Josh Bloch
 253  */
 254 public interface AnnotatedElement {
 255     /**
 256      * Returns true if an annotation for the specified type
 257      * is <em>present</em> on this element, else false.  This method
 258      * is designed primarily for convenient access to marker annotations.
 259      *
 260      * <p>The truth value returned by this method is equivalent to:
 261      * {@code getAnnotation(annotationClass) != null}
 262      *
 263      * <p>The body of the default method is specified to be the code
 264      * above.
 265      *
 266      * @param annotationClass the Class object corresponding to the
 267      *        annotation type
 268      * @return true if an annotation for the specified annotation
 269      *     type is present on this element, else false
 270      * @throws NullPointerException if the given annotation class is null
 271      * @since 1.5
 272      */
 273     default boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {
 274         return getAnnotation(annotationClass) != null;
 275     }
 276 
 277    /**
 278      * Returns this element's annotation for the specified type if
 279      * such an annotation is <em>present</em>, else null.
 280      *
 281      * @param <T> the type of the annotation to query for and return if present
 282      * @param annotationClass the Class object corresponding to the
 283      *        annotation type
 284      * @return this element's annotation for the specified annotation type if
 285      *     present on this element, else null
 286      * @throws NullPointerException if the given annotation class is null
 287      * @since 1.5
 288      */
 289     <T extends Annotation> T getAnnotation(Class<T> annotationClass);
 290 
 291     /**
 292      * Returns annotations that are <em>present</em> on this element.
 293      *
 294      * If there are no annotations <em>present</em> on this element, the return
 295      * value is an array of length 0.
 296      *
 297      * The caller of this method is free to modify the returned array; it will
 298      * have no effect on the arrays returned to other callers.
 299      *
 300      * @return annotations present on this element
 301      * @since 1.5
 302      */
 303     Annotation[] getAnnotations();
 304 
 305     /**
 306      * Returns annotations that are <em>associated</em> with this element.
 307      *
 308      * If there are no annotations <em>associated</em> with this element, the return
 309      * value is an array of length 0.
 310      *
 311      * The difference between this method and {@link #getAnnotation(Class)}
 312      * is that this method detects if its argument is a <em>repeatable
 313      * annotation type</em> (JLS 9.6), and if so, attempts to find one or
 314      * more annotations of that type by "looking through" a container
 315      * annotation.
 316      *
 317      * The caller of this method is free to modify the returned array; it will
 318      * have no effect on the arrays returned to other callers.
 319      *
 320      * @implSpec The default implementation first calls {@link
 321      * #getDeclaredAnnotationsByType(Class)} passing {@code
 322      * annotationClass} as the argument. If the returned array has
 323      * length greater than zero, the array is returned. If the returned
 324      * array is zero-length and this {@code AnnotatedElement} is a
 325      * class and the argument type is an inheritable annotation type,
 326      * and the superclass of this {@code AnnotatedElement} is non-null,
 327      * then the returned result is the result of calling {@link
 328      * #getAnnotationsByType(Class)} on the superclass with {@code
 329      * annotationClass} as the argument. Otherwise, a zero-length
 330      * array is returned.
 331      *
 332      * @param <T> the type of the annotation to query for and return if present
 333      * @param annotationClass the Class object corresponding to the
 334      *        annotation type
 335      * @return all this element's annotations for the specified annotation type if
 336      *     associated with this element, else an array of length zero
 337      * @throws NullPointerException if the given annotation class is null
 338      * @since 1.8
 339      */
 340     default <T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass) {
 341          /*
 342           * Definition of associated: directly or indirectly present OR
 343           * neither directly nor indirectly present AND the element is
 344           * a Class, the annotation type is inheritable, and the
 345           * annotation type is associated with the superclass of the
 346           * element.
 347           */
 348          T[] result = getDeclaredAnnotationsByType(annotationClass);
 349 
 350          if (result.length == 0 && // Neither directly nor indirectly present
 351              this instanceof Class && // the element is a class
 352              AnnotationType.getInstance(annotationClass).isInherited()) { // Inheritable
 353              Class<?> superClass = ((Class<?>) this).getSuperclass();
 354              if (superClass != null) {
 355                  // Determine if the annotation is associated with the
 356                  // superclass
 357                  result = superClass.getAnnotationsByType(annotationClass);
 358              }
 359          }
 360 
 361          return result;
 362      }
 363 
 364     /**
 365      * Returns this element's annotation for the specified type if
 366      * such an annotation is <em>directly present</em>, else null.
 367      *
 368      * This method ignores inherited annotations. (Returns null if no
 369      * annotations are directly present on this element.)
 370      *
 371      * @implSpec The default implementation first performs a null check
 372      * and then loops over the results of {@link
 373      * #getDeclaredAnnotations} returning the first annotation whose
 374      * annotation type matches the argument type.
 375      *
 376      * @param <T> the type of the annotation to query for and return if directly present
 377      * @param annotationClass the Class object corresponding to the
 378      *        annotation type
 379      * @return this element's annotation for the specified annotation type if
 380      *     directly present on this element, else null
 381      * @throws NullPointerException if the given annotation class is null
 382      * @since 1.8
 383      */
 384     default <T extends Annotation> T getDeclaredAnnotation(Class<T> annotationClass) {
 385          Objects.requireNonNull(annotationClass);
 386          // Loop over all directly-present annotations looking for a matching one
 387          for (Annotation annotation : getDeclaredAnnotations()) {
 388              if (annotationClass.equals(annotation.annotationType())) {
 389                  // More robust to do a dynamic cast at runtime instead
 390                  // of compile-time only.
 391                  return annotationClass.cast(annotation);
 392              }
 393          }
 394          return null;
 395      }
 396 
 397     /**
 398      * Returns this element's annotation(s) for the specified type if
 399      * such annotations are either <em>directly present</em> or
 400      * <em>indirectly present</em>. This method ignores inherited
 401      * annotations.
 402      *
 403      * If there are no specified annotations directly or indirectly
 404      * present on this element, the return value is an array of length
 405      * 0.
 406      *
 407      * The difference between this method and {@link
 408      * #getDeclaredAnnotation(Class)} is that this method detects if its
 409      * argument is a <em>repeatable annotation type</em> (JLS 9.6), and if so,
 410      * attempts to find one or more annotations of that type by "looking
 411      * through" a container annotation if one is present.
 412      *
 413      * The caller of this method is free to modify the returned array; it will
 414      * have no effect on the arrays returned to other callers.
 415      *
 416      * @implSpec The default implementation may call {@link
 417      * #getDeclaredAnnotation(Class)} one or more times to find a
 418      * directly present annotation and, if the annotation type is
 419      * repeatable, to find a container annotation. If annotations of
 420      * the annotation type {@code annotationClass} are found to be both
 421      * directly and indirectly present, then {@link
 422      * #getDeclaredAnnotations()} will get called to determine the
 423      * order of the elements in the returned array.
 424      *
 425      * <p>Alternatively, the default implementation may call {@link
 426      * #getDeclaredAnnotations()} a single time and the returned array
 427      * examined for both directly and indirectly present
 428      * annotations. The results of calling {@link
 429      * #getDeclaredAnnotations()} are assumed to be consistent with the
 430      * results of calling {@link #getDeclaredAnnotation(Class)}.
 431      *
 432      * @param <T> the type of the annotation to query for and return
 433      * if directly or indirectly present
 434      * @param annotationClass the Class object corresponding to the
 435      *        annotation type
 436      * @return all this element's annotations for the specified annotation type if
 437      *     directly or indirectly present on this element, else an array of length zero
 438      * @throws NullPointerException if the given annotation class is null
 439      * @since 1.8
 440      */
 441     default <T extends Annotation> T[] getDeclaredAnnotationsByType(Class<T> annotationClass) {
 442         Objects.requireNonNull(annotationClass);
 443         return AnnotationSupport.
 444             getDirectlyAndIndirectlyPresent(Arrays.stream(getDeclaredAnnotations()).
 445                                             collect(Collectors.toMap(Annotation::annotationType,
 446                                                                      Function.identity(),
 447                                                                      ((first,second) -> first),
 448                                                                      LinkedHashMap::new)),
 449                                             annotationClass);
 450     }
 451 
 452     /**
 453      * Returns annotations that are <em>directly present</em> on this element.
 454      * This method ignores inherited annotations.
 455      *
 456      * If there are no annotations <em>directly present</em> on this element,
 457      * the return value is an array of length 0.
 458      *
 459      * The caller of this method is free to modify the returned array; it will
 460      * have no effect on the arrays returned to other callers.
 461      *
 462      * @return annotations directly present on this element
 463      * @since 1.5
 464      */
 465     Annotation[] getDeclaredAnnotations();
 466 }