src/share/classes/java/lang/reflect/AnnotatedElement.java

Print this page




  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 
  31 /**
  32  * Represents an annotated element of the program currently running in this
  33  * VM.  This interface allows annotations to be read reflectively.  All
  34  * annotations returned by methods in this interface are immutable and
  35  * serializable. The arrays returned by methods of this interface may be modified
  36  * by callers without affecting the arrays returned to other callers.
  37  *
  38  * <p>The {@link #getAnnotationsByType(Class)} and {@link
  39  * #getDeclaredAnnotationsByType(Class)} methods support multiple
  40  * annotations of the same type on an element. If the argument to
  41  * either method is a repeatable annotation type (JLS 9.6), then the
  42  * method will "look through" a container annotation (JLS 9.7), if
  43  * present, and return any annotations inside the container. Container
  44  * annotations may be generated at compile-time to wrap multiple
  45  * annotations of the argument type.
  46  *
  47  * <p>The terms <em>directly present</em>, <em>indirectly present</em>,
  48  * <em>present</em>, and <em>associated</em> are used throughout this
  49  * interface to describe precisely which annotations are returned by


 205      * @return annotations present on this element
 206      * @since 1.5
 207      */
 208     Annotation[] getAnnotations();
 209 
 210     /**
 211      * Returns annotations that are <em>associated</em> with this element.
 212      *
 213      * If there are no annotations <em>associated</em> with this element, the return
 214      * value is an array of length 0.
 215      *
 216      * The difference between this method and {@link #getAnnotation(Class)}
 217      * is that this method detects if its argument is a <em>repeatable
 218      * annotation type</em> (JLS 9.6), and if so, attempts to find one or
 219      * more annotations of that type by "looking through" a container
 220      * annotation.
 221      *
 222      * The caller of this method is free to modify the returned array; it will
 223      * have no effect on the arrays returned to other callers.
 224      *










 225      * @param <T> the type of the annotation to query for and return if present
 226      * @param annotationClass the Class object corresponding to the
 227      *        annotation type
 228      * @return all this element's annotations for the specified annotation type if
 229      *     associated with this element, else an array of length zero
 230      * @throws NullPointerException if the given annotation class is null
 231      * @since 1.8
 232      */
 233     <T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass);






















 234 
 235     /**
 236      * Returns this element's annotation for the specified type if
 237      * such an annotation is <em>directly present</em>, else null.
 238      *
 239      * This method ignores inherited annotations. (Returns null if no
 240      * annotations are directly present on this element.)
 241      *





 242      * @param <T> the type of the annotation to query for and return if directly present
 243      * @param annotationClass the Class object corresponding to the
 244      *        annotation type
 245      * @return this element's annotation for the specified annotation type if
 246      *     directly present on this element, else null
 247      * @throws NullPointerException if the given annotation class is null
 248      * @since 1.8
 249      */
 250     <T extends Annotation> T getDeclaredAnnotation(Class<T> annotationClass);











 251 
 252     /**
 253      * Returns this element's annotation(s) for the specified type if
 254      * such annotations are either <em>directly present</em> or
 255      * <em>indirectly present</em>. This method ignores inherited
 256      * annotations.
 257      *
 258      * If there are no specified annotations directly or indirectly
 259      * present on this element, the return value is an array of length
 260      * 0.
 261      *
 262      * The difference between this method and {@link
 263      * #getDeclaredAnnotation(Class)} is that this method detects if its
 264      * argument is a <em>repeatable annotation type</em> (JLS 9.6), and if so,
 265      * attempts to find one or more annotations of that type by "looking
 266      * through" a container annotation if one is present.
 267      *
 268      * The caller of this method is free to modify the returned array; it will
 269      * have no effect on the arrays returned to other callers.
 270      *













 271      * @param <T> the type of the annotation to query for and return
 272      * if directly or indirectly present
 273      * @param annotationClass the Class object corresponding to the
 274      *        annotation type
 275      * @return all this element's annotations for the specified annotation type if
 276      *     directly or indirectly present on this element, else an array of length zero
 277      * @throws NullPointerException if the given annotation class is null
 278      * @since 1.8
 279      */
 280     <T extends Annotation> T[] getDeclaredAnnotationsByType(Class<T> annotationClass);


























































































 281 
 282     /**
 283      * Returns annotations that are <em>directly present</em> on this element.
 284      * This method ignores inherited annotations.
 285      *
 286      * If there are no annotations <em>directly present</em> on this element,
 287      * the return value is an array of length 0.
 288      *
 289      * The caller of this method is free to modify the returned array; it will
 290      * have no effect on the arrays returned to other callers.
 291      *
 292      * @return annotations directly present on this element
 293      * @since 1.5
 294      */
 295     Annotation[] getDeclaredAnnotations();
 296 }


  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


 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)} on the argument type. If
 231      * the returned array has size greater than zero, the array is
 232      * returned. If the returned array has size zero and this {@code
 233      * AnnotatedElement} is a class and the argument type is an
 234      * inheritable annotation, and the superclass of this {@code
 235      * AnnoatedElement} is non-null, then the result of {@code
 236      * getAnnotationsByType(annotationClass)} on the superclass is
 237      * returned. Otherwise, a zero-length array is returned.
 238      *
 239      * @param <T> the type of the annotation to query for and return if present
 240      * @param annotationClass the Class object corresponding to the
 241      *        annotation type
 242      * @return all this element's annotations for the specified annotation type if
 243      *     associated with this element, else an array of length zero
 244      * @throws NullPointerException if the given annotation class is null
 245      * @since 1.8
 246      */
 247     default <T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass) {
 248          /*
 249           * Definition of associated: directly or indirectly present OR
 250           * neither directly nor indirectly present AND the element is
 251           * a Class, the annotation type is inheritable, and the
 252           * annotation type is associated with the superclass of the
 253           * element.
 254           */
 255          T[] result = getDeclaredAnnotationsByType(annotationClass);
 256 
 257          if (result.length == 0 && // Neither directly nor indirectly present
 258              this instanceof Class && // the element is a class
 259              AnnotationType.getInstance(annotationClass).isInherited()) { // Inheritable
 260              Class<?> superClass = ((Class<?>) this).getSuperclass();
 261              if (superClass != null) {
 262                  // Determine if the annotation is associated with the
 263                  // superclass
 264                  result = superClass.getAnnotationsByType(annotationClass);
 265              }
 266          }
 267 
 268          return result;
 269      }
 270     
 271     /**
 272      * Returns this element's annotation for the specified type if
 273      * such an annotation is <em>directly present</em>, else null.
 274      *
 275      * This method ignores inherited annotations. (Returns null if no
 276      * annotations are directly present on this element.)
 277      *
 278      * @implSpec The default implementation first performs a null check
 279      * and then loops over the results of {@link
 280      * getDeclaredAnnotations} returning the first annotation whose
 281      * annotation type matches the argument type.
 282      *
 283      * @param <T> the type of the annotation to query for and return if directly present
 284      * @param annotationClass the Class object corresponding to the
 285      *        annotation type
 286      * @return this element's annotation for the specified annotation type if
 287      *     directly present on this element, else null
 288      * @throws NullPointerException if the given annotation class is null
 289      * @since 1.8
 290      */
 291     default <T extends Annotation> T getDeclaredAnnotation(Class<T> annotationClass) {
 292          Objects.requireNonNull(annotationClass);
 293          // Loop over all directly-present annotations looking for a matching one
 294          for (Annotation annotation : getDeclaredAnnotations()) {
 295              if (annotationClass.equals(annotation.annotationType())) {
 296                  // More robust to do a dynamic cast at runtime instead
 297                  // of compile-time only.
 298                  return annotationClass.cast(annotation);
 299              }
 300          }
 301          return null; 
 302      }
 303 
 304     /**
 305      * Returns this element's annotation(s) for the specified type if
 306      * such annotations are either <em>directly present</em> or
 307      * <em>indirectly present</em>. This method ignores inherited
 308      * annotations.
 309      *
 310      * If there are no specified annotations directly or indirectly
 311      * present on this element, the return value is an array of length
 312      * 0.
 313      *
 314      * The difference between this method and {@link
 315      * #getDeclaredAnnotation(Class)} is that this method detects if its
 316      * argument is a <em>repeatable annotation type</em> (JLS 9.6), and if so,
 317      * attempts to find one or more annotations of that type by "looking
 318      * through" a container annotation if one is present.
 319      *
 320      * The caller of this method is free to modify the returned array; it will
 321      * have no effect on the arrays returned to other callers.
 322      *
 323      * @implSpec The default implementation may call {@link
 324      * #getDeclaredAnnotation(Class)} one or more times to find a
 325      * directly present annotation and, if the annotation type is
 326      * repeatable, to find a container annotation. If the annotation
 327      * type is both directly and indirectly present, {@link
 328      * getDeclaredAnnotations()} will get called to determine the
 329      * order of the elements in the returned array. Alternatively,
 330      * {@link getDeclaredAnnotations()} may be called a single time
 331      * and the returned array examined for both directly and
 332      * indirectly present annotations. The results of calling {@link
 333      * getDeclaredAnnotations()} are assumed to be consistent with the
 334      * results of calling {@code #getDeclaredAnnotation}
 335      *
 336      * @param <T> the type of the annotation to query for and return
 337      * if directly or indirectly present
 338      * @param annotationClass the Class object corresponding to the
 339      *        annotation type
 340      * @return all this element's annotations for the specified annotation type if
 341      *     directly or indirectly present on this element, else an array of length zero
 342      * @throws NullPointerException if the given annotation class is null
 343      * @since 1.8
 344      */
 345     default <T extends Annotation> T[] getDeclaredAnnotationsByType(Class<T> annotationClass)
 346   {
 347          Objects.requireNonNull(annotationClass);
 348          int resultSize = 0;
 349          T directlyPresent = getDeclaredAnnotation(annotationClass);
 350 
 351          if (directlyPresent != null) {
 352              resultSize++;
 353          }
 354 
 355          Repeatable repeatable = annotationClass.getAnnotation(Repeatable.class);
 356          if (repeatable == null) {
 357              @SuppressWarnings("unchecked")
 358              T[] returnValue =  (T[]) Array.newInstance(annotationClass, resultSize);
 359              if (directlyPresent != null)
 360                  returnValue[0] = directlyPresent;
 361              return returnValue;
 362          } else {
 363              // directlyPresent may or may not be null
 364 
 365              // Look through a container to see if an annotation is
 366              // indirectly present
 367              Class<? extends Annotation> containerType = repeatable.value();
 368              Annotation container =  getDeclaredAnnotation(containerType);
 369              T[] indirectlyPresent = null;
 370 
 371              if (container != null) {
 372                  indirectlyPresent = AnnotationSupport.getValueArray(container);
 373                  resultSize += indirectlyPresent.length;
 374              }
 375 
 376              // Final result size is known
 377 
 378              // todo: review comment for accuracy...
 379              /*
 380               * If resultSize is 0, indirectlyPresent is either
 381               * assigned to the result of the initial Array.newInstance
 382               * call or indirectlyPresent is assigned to a zero-length
 383               * value array from an empty container annotation. In
 384               * either case, a zero-length array is immutable and does
 385               * not need to reallocated before being returned.
 386               *
 387               * If resultSize is nonzero, then indirectlyPresent points
 388               * to the result calling a method on an annotation and
 389               * annotations are required to implement a no sharing
 390               * policy. Therefore, it is not required to copy the
 391               * elements of indirectlyPresent into a new array of the
 392               * same size.
 393               */
 394              if (indirectlyPresent == null || indirectlyPresent.length == 0) {
 395                  @SuppressWarnings("unchecked")
 396                  T[] returnValue = (T[]) Array.newInstance(annotationClass, resultSize);
 397                  if (resultSize == 1)
 398                      returnValue[0] = directlyPresent;
 399                  return returnValue;
 400              } else {
 401                  //                 assert indirectlyPresent != null && indirectlyPresent.length > 0;
 402 
 403                  if (resultSize == indirectlyPresent.length){
 404                      //                     assert resultSize == 0 || directlyPresent == null;
 405                      return indirectlyPresent;
 406                  } else {
 407                      //                     assert directlyPresent != null && indirectlyPresent.length > 0;
 408                      @SuppressWarnings("unchecked")
 409                      T[] returnValue = (T[]) Array.newInstance(annotationClass, resultSize);
 410 
 411                      // Determine whether the directly present annotation
 412                      // comes before or after the indirectly present ones.
 413 
 414                      int indirectOffset = 0;
 415 
 416                      for (Annotation a : getDeclaredAnnotations()) {
 417                          if (a.annotationType().equals(annotationClass)) {
 418                              indirectOffset = 1;
 419                              break;
 420                          } else if (a.annotationType().equals(containerType)) {
 421                              break;
 422                          }
 423                      }
 424 
 425                      for (int i = 0; i < indirectlyPresent.length; i++) {
 426                          returnValue[i + indirectOffset] = indirectlyPresent[i];
 427                      }
 428 
 429                      returnValue[(indirectOffset == 1) ? 0 : resultSize - 1] = directlyPresent;
 430                      return returnValue;
 431                  }
 432              }
 433          }
 434      }
 435 
 436 
 437     /**
 438      * Returns annotations that are <em>directly present</em> on this element.
 439      * This method ignores inherited annotations.
 440      *
 441      * If there are no annotations <em>directly present</em> on this element,
 442      * the return value is an array of length 0.
 443      *
 444      * The caller of this method is free to modify the returned array; it will
 445      * have no effect on the arrays returned to other callers.
 446      *
 447      * @return annotations directly present on this element
 448      * @since 1.5
 449      */
 450     Annotation[] getDeclaredAnnotations();
 451 }