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