1 /*
   2  * Copyright (c) 2003, 2013, 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.Objects;
  32 import sun.reflect.annotation.AnnotationSupport;
  33 import sun.reflect.annotation.AnnotationType;
  34 
  35 /**
  36  * Represents an annotated element of the program currently running in this
  37  * VM.  This interface allows annotations to be read reflectively.  All
  38  * annotations returned by methods in this interface are immutable and
  39  * serializable. The arrays returned by methods of this interface may be modified
  40  * by callers without affecting the arrays returned to other callers.
  41  *
  42  * <p>The {@link #getAnnotationsByType(Class)} and {@link
  43  * #getDeclaredAnnotationsByType(Class)} methods support multiple
  44  * annotations of the same type on an element. If the argument to
  45  * either method is a repeatable annotation type (JLS 9.6), then the
  46  * method will "look through" a container annotation (JLS 9.7), if
  47  * present, and return any annotations inside the container. Container
  48  * annotations may be generated at compile-time to wrap multiple
  49  * annotations of the argument type.
  50  *
  51  * <p>The terms <em>directly present</em>, <em>indirectly present</em>,
  52  * <em>present</em>, and <em>associated</em> are used throughout this
  53  * interface to describe precisely which annotations are returned by
  54  * methods:
  55  *
  56  * <ul>
  57  *
  58  * <li> An annotation <i>A</i> is <em>directly present</em> on an
  59  * element <i>E</i> if <i>E</i> has a {@code
  60  * RuntimeVisibleAnnotations} or {@code
  61  * RuntimeVisibleParameterAnnotations} or {@code
  62  * RuntimeVisibleTypeAnnotations} attribute, and the attribute
  63  * contains <i>A</i>.
  64  *
  65  * <li>An annotation <i>A</i> is <em>indirectly present</em> on an
  66  * element <i>E</i> if <i>E</i> has a {@code RuntimeVisibleAnnotations} or
  67  * {@code RuntimeVisibleParameterAnnotations} or {@code RuntimeVisibleTypeAnnotations}
  68  * attribute, and <i>A</i> 's type is repeatable, and the attribute contains
  69  * exactly one annotation whose value element contains <i>A</i> and whose
  70  * type is the containing annotation type of <i>A</i> 's type.
  71  *
  72  * <li>An annotation <i>A</i> is present on an element <i>E</i> if either:
  73  *
  74  * <ul>
  75  *
  76  * <li><i>A</i> is directly present on <i>E</i>; or
  77  *
  78  * <li>No annotation of <i>A</i> 's type is directly present on
  79  * <i>E</i>, and <i>E</i> is a class, and <i>A</i> 's type is
  80  * inheritable, and <i>A</i> is present on the superclass of <i>E</i>.
  81  *
  82  * </ul>
  83  *
  84  * <li>An annotation <i>A</i> is <em>associated</em> with an element <i>E</i>
  85  * if either:
  86  *
  87  * <ul>
  88  *
  89  * <li><i>A</i> is directly or indirectly present on <i>E</i>; or
  90  *
  91  * <li>No annotation of <i>A</i> 's type is directly or indirectly
  92  * present on <i>E</i>, and <i>E</i> is a class, and <i>A</i>'s type
  93  * is inheritable, and <i>A</i> is associated with the superclass of
  94  * <i>E</i>.
  95  *
  96  * </ul>
  97  *
  98  * </ul>
  99  *
 100  * <p>The table below summarizes which kind of annotation presence
 101  * different methods in this interface examine.
 102  *
 103  * <table border>
 104  * <caption>Overview of kind of presence detected by different AnnotatedElement methods</caption>
 105  * <tr><th colspan=2></th><th colspan=4>Kind of Presence</th>
 106  * <tr><th colspan=2>Method</th><th>Directly Present</th><th>Indirectly Present</th><th>Present</th><th>Associated</th>
 107  * <tr><td align=right>{@code T}</td><td>{@link #getAnnotation(Class) getAnnotation(Class&lt;T&gt;)}
 108  * <td></td><td></td><td>X</td><td></td>
 109  * </tr>
 110  * <tr><td align=right>{@code Annotation[]}</td><td>{@link #getAnnotations getAnnotations()}
 111  * <td></td><td></td><td>X</td><td></td>
 112  * </tr>
 113  * <tr><td align=right>{@code T[]}</td><td>{@link #getAnnotationsByType(Class) getAnnotationsByType(Class&lt;T&gt;)}
 114  * <td></td><td></td><td></td><td>X</td>
 115  * </tr>
 116  * <tr><td align=right>{@code T}</td><td>{@link #getDeclaredAnnotation(Class) getDeclaredAnnotation(Class&lt;T&gt;)}
 117  * <td>X</td><td></td><td></td><td></td>
 118  * </tr>
 119  * <tr><td align=right>{@code Annotation[]}</td><td>{@link #getDeclaredAnnotations getDeclaredAnnotations()}
 120  * <td>X</td><td></td><td></td><td></td>
 121  * </tr>
 122  * <tr><td align=right>{@code T[]}</td><td>{@link #getDeclaredAnnotationsByType(Class) getDeclaredAnnotationsByType(Class&lt;T&gt;)}
 123  * <td>X</td><td>X</td><td></td><td></td>
 124  * </tr>
 125  * </table>
 126  *
 127  * <p>For an invocation of {@code get[Declared]AnnotationsByType( Class <
 128  * T >)}, the order of annotations which are directly or indirectly
 129  * present on an element <i>E</i> is computed as if indirectly present
 130  * annotations on <i>E</i> are directly present on <i>E</i> in place
 131  * of their container annotation, in the order in which they appear in
 132  * the value element of the container annotation.
 133 
 134  * <p>If an annotation returned by a method in this interface contains
 135  * (directly or indirectly) a {@link Class}-valued member referring to
 136  * a class that is not accessible in this VM, attempting to read the class
 137  * by calling the relevant Class-returning method on the returned annotation
 138  * will result in a {@link TypeNotPresentException}.
 139  *
 140  * <p>Similarly, attempting to read an enum-valued member will result in
 141  * a {@link EnumConstantNotPresentException} if the enum constant in the
 142  * annotation is no longer present in the enum type.
 143  *
 144  * <p>If an annotation type <i>T</i> is (meta-)annotated with an
 145  * {@code @Repeatable} annotation whose value element indicates a type
 146  * <i>TC</i>, but <i>TC</i> does not declare a {@code value()} method
 147  * with a return type of <i>T</i>{@code []}, then an exception of type
 148  * {@link java.lang.annotation.AnnotationFormatError} is thrown.
 149  *
 150  * <p>Finally, attempting to read a member whose definition has evolved
 151  * incompatibly will result in a {@link
 152  * java.lang.annotation.AnnotationTypeMismatchException} or an
 153  * {@link java.lang.annotation.IncompleteAnnotationException}.
 154  *
 155  * @see java.lang.EnumConstantNotPresentException
 156  * @see java.lang.TypeNotPresentException
 157  * @see AnnotationFormatError
 158  * @see java.lang.annotation.AnnotationTypeMismatchException
 159  * @see java.lang.annotation.IncompleteAnnotationException
 160  * @since 1.5
 161  * @author Josh Bloch
 162  */
 163 public interface AnnotatedElement {
 164     /**
 165      * Returns true if an annotation for the specified type
 166      * is <em>present</em> on this element, else false.  This method
 167      * is designed primarily for convenient access to marker annotations.
 168      *
 169      * <p>The truth value returned by this method is equivalent to:
 170      * {@code getAnnotation(annotationClass) != null}
 171      *
 172      * <p>The body of the default method is specified to be the code
 173      * above.
 174      *
 175      * @param annotationClass the Class object corresponding to the
 176      *        annotation type
 177      * @return true if an annotation for the specified annotation
 178      *     type is present on this element, else false
 179      * @throws NullPointerException if the given annotation class is null
 180      * @since 1.5
 181      */
 182     default boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {
 183         return getAnnotation(annotationClass) != null;
 184     }
 185 
 186    /**
 187      * Returns this element's annotation for the specified type if
 188      * such an annotation is <em>present</em>, else null.
 189      *
 190      * @param <T> the type of the annotation to query for and return if present
 191      * @param annotationClass the Class object corresponding to the
 192      *        annotation type
 193      * @return this element's annotation for the specified annotation type if
 194      *     present on this element, else null
 195      * @throws NullPointerException if the given annotation class is null
 196      * @since 1.5
 197      */
 198     <T extends Annotation> T getAnnotation(Class<T> annotationClass);
 199 
 200     /**
 201      * Returns annotations that are <em>present</em> on this element.
 202      *
 203      * If there are no annotations <em>present</em> on this element, the return
 204      * value is an array of length 0.
 205      *
 206      * The caller of this method is free to modify the returned array; it will
 207      * have no effect on the arrays returned to other callers.
 208      *
 209      * @return annotations present on this element
 210      * @since 1.5
 211      */
 212     Annotation[] getAnnotations();
 213 
 214     /**
 215      * Returns annotations that are <em>associated</em> with this element.
 216      *
 217      * If there are no annotations <em>associated</em> with this element, the return
 218      * value is an array of length 0.
 219      *
 220      * The difference between this method and {@link #getAnnotation(Class)}
 221      * is that this method detects if its argument is a <em>repeatable
 222      * annotation type</em> (JLS 9.6), and if so, attempts to find one or
 223      * more annotations of that type by "looking through" a container
 224      * annotation.
 225      *
 226      * The caller of this method is free to modify the returned array; it will
 227      * have no effect on the arrays returned to other callers.
 228      *
 229      * @implSpec The default implementation first calls {@link
 230      * #getDeclaredAnnotationsByType(Class)} passing {@code
 231      * annotationClass} as the argument. If the returned array has
 232      * size greater than zero, the array is returned. If the returned
 233      * array has size zero and this {@code AnnotatedElement} is a
 234      * class and the argument type is an inheritable annotation type,
 235      * and the superclass of this {@code AnnoatedElement} is non-null,
 236      * then the returned result is the result of calling {@code
 237      * getAnnotationsByType} on the superclass with {@code
 238      * annotationClass} as the argument. Otherwise, a zero-length
 239      * array is returned.
 240      *
 241      * @param <T> the type of the annotation to query for and return if present
 242      * @param annotationClass the Class object corresponding to the
 243      *        annotation type
 244      * @return all this element's annotations for the specified annotation type if
 245      *     associated with this element, else an array of length zero
 246      * @throws NullPointerException if the given annotation class is null
 247      * @since 1.8
 248      */
 249     default <T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass) {
 250          /*
 251           * Definition of associated: directly or indirectly present OR
 252           * neither directly nor indirectly present AND the element is
 253           * a Class, the annotation type is inheritable, and the
 254           * annotation type is associated with the superclass of the
 255           * element.
 256           */
 257          T[] result = getDeclaredAnnotationsByType(annotationClass);
 258 
 259          if (result.length == 0 && // Neither directly nor indirectly present
 260              this instanceof Class && // the element is a class
 261              AnnotationType.getInstance(annotationClass).isInherited()) { // Inheritable
 262              Class<?> superClass = ((Class<?>) this).getSuperclass();
 263              if (superClass != null) {
 264                  // Determine if the annotation is associated with the
 265                  // superclass
 266                  result = superClass.getAnnotationsByType(annotationClass);
 267              }
 268          }
 269 
 270          return result;
 271      }
 272     
 273     /**
 274      * Returns this element's annotation for the specified type if
 275      * such an annotation is <em>directly present</em>, else null.
 276      *
 277      * This method ignores inherited annotations. (Returns null if no
 278      * annotations are directly present on this element.)
 279      *
 280      * @implSpec The default implementation first performs a null check
 281      * and then loops over the results of {@link
 282      * #getDeclaredAnnotations} returning the first annotation whose
 283      * annotation type matches the argument type.
 284      *
 285      * @param <T> the type of the annotation to query for and return if directly present
 286      * @param annotationClass the Class object corresponding to the
 287      *        annotation type
 288      * @return this element's annotation for the specified annotation type if
 289      *     directly present on this element, else null
 290      * @throws NullPointerException if the given annotation class is null
 291      * @since 1.8
 292      */
 293     default <T extends Annotation> T getDeclaredAnnotation(Class<T> annotationClass) {
 294          Objects.requireNonNull(annotationClass);
 295          // Loop over all directly-present annotations looking for a matching one
 296          for (Annotation annotation : getDeclaredAnnotations()) {
 297              if (annotationClass.equals(annotation.annotationType())) {
 298                  // More robust to do a dynamic cast at runtime instead
 299                  // of compile-time only.
 300                  return annotationClass.cast(annotation);
 301              }
 302          }
 303          return null; 
 304      }
 305 
 306     /**
 307      * Returns this element's annotation(s) for the specified type if
 308      * such annotations are either <em>directly present</em> or
 309      * <em>indirectly present</em>. This method ignores inherited
 310      * annotations.
 311      *
 312      * If there are no specified annotations directly or indirectly
 313      * present on this element, the return value is an array of length
 314      * 0.
 315      *
 316      * The difference between this method and {@link
 317      * #getDeclaredAnnotation(Class)} is that this method detects if its
 318      * argument is a <em>repeatable annotation type</em> (JLS 9.6), and if so,
 319      * attempts to find one or more annotations of that type by "looking
 320      * through" a container annotation if one is present.
 321      *
 322      * The caller of this method is free to modify the returned array; it will
 323      * have no effect on the arrays returned to other callers.
 324      *
 325      * @implSpec The default implementation may call {@link
 326      * #getDeclaredAnnotation(Class)} one or more times to find a
 327      * directly present annotation and, if the annotation type is
 328      * repeatable, to find a container annotation. If annotations of
 329      * the annotation type {@code annotationClass} are found to be both
 330      * directly and indirectly present, then {@link
 331      * #getDeclaredAnnotations()} will get called to determine the
 332      * order of the elements in the returned array.
 333      *
 334      * <p>Alternatively, the default implementation may call {@link
 335      * #getDeclaredAnnotations()} a single time and the returned array
 336      * examined for both directly and indirectly present
 337      * annotations. The results of calling {@link
 338      * #getDeclaredAnnotations()} are assumed to be consistent with the
 339      * results of calling {@link #getDeclaredAnnotation(Class)}.
 340      *
 341      * @param <T> the type of the annotation to query for and return
 342      * if directly or indirectly present
 343      * @param annotationClass the Class object corresponding to the
 344      *        annotation type
 345      * @return all this element's annotations for the specified annotation type if
 346      *     directly or indirectly present on this element, else an array of length zero
 347      * @throws NullPointerException if the given annotation class is null
 348      * @since 1.8
 349      */
 350     default <T extends Annotation> T[] getDeclaredAnnotationsByType(Class<T> annotationClass) {
 351         Objects.requireNonNull(annotationClass);
 352         int resultSize = 0;
 353         T directlyPresent = getDeclaredAnnotation(annotationClass);
 354         
 355         if (directlyPresent != null) {
 356             resultSize++;
 357         }
 358 
 359         Repeatable repeatable = annotationClass.getAnnotation(Repeatable.class);
 360         if (repeatable == null) {
 361             @SuppressWarnings("unchecked")
 362             T[] returnValue =  (T[]) Array.newInstance(annotationClass, resultSize);
 363             if (directlyPresent != null)
 364                 returnValue[0] = directlyPresent;
 365             return returnValue;
 366         } else {
 367             // directlyPresent may or may not be null
 368             
 369             // Look through a container to see if an annotation is
 370             // indirectly present
 371             Class<? extends Annotation> containerType = repeatable.value();
 372             Annotation container =  getDeclaredAnnotation(containerType);
 373             T[] indirectlyPresent = null;
 374 
 375             if (container != null) {
 376                 indirectlyPresent = AnnotationSupport.getValueArray(container);
 377                 resultSize += indirectlyPresent.length;
 378             }
 379 
 380             // Final result size is known
 381 
 382             // todo: review comment for accuracy...
 383             /*
 384              * If resultSize is 0, indirectlyPresent is either
 385              * assigned to the result of the initial Array.newInstance
 386              * call or indirectlyPresent is assigned to a zero-length
 387              * value array from an empty container annotation. In
 388              * either case, a zero-length array is immutable and does
 389              * not need to reallocated before being returned.
 390              *
 391              * If resultSize is nonzero, then indirectlyPresent points
 392              * to the result calling a method on an annotation and
 393              * annotations are required to implement a no sharing
 394              * policy. Therefore, it is not required to copy the
 395              * elements of indirectlyPresent into a new array of the
 396              * same size.
 397              */
 398             if (indirectlyPresent == null || indirectlyPresent.length == 0) {
 399                 @SuppressWarnings("unchecked")
 400                 T[] returnValue = (T[]) Array.newInstance(annotationClass, resultSize);
 401                 if (resultSize == 1)
 402                     returnValue[0] = directlyPresent;
 403                 return returnValue;
 404             } else {
 405                 // assert indirectlyPresent != null && indirectlyPresent.length > 0;
 406 
 407                 if (resultSize == indirectlyPresent.length){
 408                     // assert directlyPresent == null;
 409                     return indirectlyPresent;
 410                 } else {
 411                     // assert directlyPresent != null && indirectlyPresent.length > 0;
 412                     @SuppressWarnings("unchecked")
 413                     T[] returnValue = (T[]) Array.newInstance(annotationClass, resultSize);
 414 
 415                     // Determine whether the directly present annotation
 416                     // comes before or after the indirectly present ones.
 417 
 418                     int indirectOffset = 0;
 419 
 420                     for (Annotation a : getDeclaredAnnotations()) {
 421                         Class<? extends Annotation> annotationType = a.annotationType();
 422                         if (annotationType.equals(annotationClass)) {
 423                             indirectOffset = 1;
 424                             break;
 425                         } else if (annotationType.equals(containerType)) {
 426                             break;
 427                         }
 428                     }
 429 
 430                     for (int i = 0; i < indirectlyPresent.length; i++) {
 431                         returnValue[i + indirectOffset] = indirectlyPresent[i];
 432                     }
 433 
 434                     returnValue[(indirectOffset == 1) ? 0 : resultSize - 1] = directlyPresent;
 435                     return returnValue;
 436                 }
 437             }
 438         }
 439     }
 440 
 441 
 442     /**
 443      * Returns annotations that are <em>directly present</em> on this element.
 444      * This method ignores inherited annotations.
 445      *
 446      * If there are no annotations <em>directly present</em> on this element,
 447      * the return value is an array of length 0.
 448      *
 449      * The caller of this method is free to modify the returned array; it will
 450      * have no effect on the arrays returned to other callers.
 451      *
 452      * @return annotations directly present on this element
 453      * @since 1.5
 454      */
 455     Annotation[] getDeclaredAnnotations();
 456 }