1 /*
   2  * Copyright (c) 1996, 2015, 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 jdk.internal.misc.SharedSecrets;
  29 import jdk.internal.reflect.CallerSensitive;
  30 import jdk.internal.reflect.FieldAccessor;
  31 import jdk.internal.reflect.Reflection;
  32 import sun.reflect.generics.repository.FieldRepository;
  33 import sun.reflect.generics.factory.CoreReflectionFactory;
  34 import sun.reflect.generics.factory.GenericsFactory;
  35 import sun.reflect.generics.scope.ClassScope;
  36 import java.lang.annotation.Annotation;
  37 import java.util.Map;
  38 import java.util.Objects;
  39 import sun.reflect.annotation.AnnotationParser;
  40 import sun.reflect.annotation.AnnotationSupport;
  41 import sun.reflect.annotation.TypeAnnotation;
  42 import sun.reflect.annotation.TypeAnnotationParser;
  43 
  44 /**
  45  * A {@code Field} provides information about, and dynamic access to, a
  46  * single field of a class or an interface.  The reflected field may
  47  * be a class (static) field or an instance field.
  48  *
  49  * <p>A {@code Field} permits widening conversions to occur during a get or
  50  * set access operation, but throws an {@code IllegalArgumentException} if a
  51  * narrowing conversion would occur.
  52  *
  53  * @see Member
  54  * @see java.lang.Class
  55  * @see java.lang.Class#getFields()
  56  * @see java.lang.Class#getField(String)
  57  * @see java.lang.Class#getDeclaredFields()
  58  * @see java.lang.Class#getDeclaredField(String)
  59  *
  60  * @author Kenneth Russell
  61  * @author Nakul Saraiya
  62  */
  63 public final
  64 class Field extends AccessibleObject implements Member {
  65 
  66     private Class<?>            clazz;
  67     private int                 slot;
  68     // This is guaranteed to be interned by the VM in the 1.4
  69     // reflection implementation
  70     private String              name;
  71     private Class<?>            type;
  72     private int                 modifiers;
  73     // Generics and annotations support
  74     private transient String    signature;
  75     // generic info repository; lazily initialized
  76     private transient FieldRepository genericInfo;
  77     private byte[]              annotations;
  78     // Cached field accessor created without override
  79     private FieldAccessor fieldAccessor;
  80     // Cached field accessor created with override
  81     private FieldAccessor overrideFieldAccessor;
  82     // For sharing of FieldAccessors. This branching structure is
  83     // currently only two levels deep (i.e., one root Field and
  84     // potentially many Field objects pointing to it.)
  85     //
  86     // If this branching structure would ever contain cycles, deadlocks can
  87     // occur in annotation code.
  88     private Field               root;
  89 
  90     // Generics infrastructure
  91 
  92     private String getGenericSignature() {return signature;}
  93 
  94     // Accessor for factory
  95     private GenericsFactory getFactory() {
  96         Class<?> c = getDeclaringClass();
  97         // create scope and factory
  98         return CoreReflectionFactory.make(c, ClassScope.make(c));
  99     }
 100 
 101     // Accessor for generic info repository
 102     private FieldRepository getGenericInfo() {
 103         // lazily initialize repository if necessary
 104         if (genericInfo == null) {
 105             // create and cache generic info repository
 106             genericInfo = FieldRepository.make(getGenericSignature(),
 107                                                getFactory());
 108         }
 109         return genericInfo; //return cached repository
 110     }
 111 
 112 
 113     /**
 114      * Package-private constructor used by ReflectAccess to enable
 115      * instantiation of these objects in Java code from the java.lang
 116      * package via sun.reflect.LangReflectAccess.
 117      */
 118     Field(Class<?> declaringClass,
 119           String name,
 120           Class<?> type,
 121           int modifiers,
 122           int slot,
 123           String signature,
 124           byte[] annotations)
 125     {
 126         this.clazz = declaringClass;
 127         this.name = name;
 128         this.type = type;
 129         this.modifiers = modifiers;
 130         this.slot = slot;
 131         this.signature = signature;
 132         this.annotations = annotations;
 133     }
 134 
 135     /**
 136      * Package-private routine (exposed to java.lang.Class via
 137      * ReflectAccess) which returns a copy of this Field. The copy's
 138      * "root" field points to this Field.
 139      */
 140     Field copy() {
 141         // This routine enables sharing of FieldAccessor objects
 142         // among Field objects which refer to the same underlying
 143         // method in the VM. (All of this contortion is only necessary
 144         // because of the "accessibility" bit in AccessibleObject,
 145         // which implicitly requires that new java.lang.reflect
 146         // objects be fabricated for each reflective call on Class
 147         // objects.)
 148         if (this.root != null)
 149             throw new IllegalArgumentException("Can not copy a non-root Field");
 150 
 151         Field res = new Field(clazz, name, type, modifiers, slot, signature, annotations);
 152         res.root = this;
 153         // Might as well eagerly propagate this if already present
 154         res.fieldAccessor = fieldAccessor;
 155         res.overrideFieldAccessor = overrideFieldAccessor;
 156 
 157         return res;
 158     }
 159 
 160     @Override
 161     @CallerSensitive
 162     public void setAccessible(boolean flag) {
 163         AccessibleObject.checkPermission();
 164         if (flag) checkCanSetAccessible(Reflection.getCallerClass());
 165         setAccessible0(flag);
 166     }
 167 
 168     @Override
 169     void checkCanSetAccessible(Class<?> caller) {
 170         checkCanSetAccessible(caller, clazz);
 171     }
 172 
 173     /**
 174      * Returns the {@code Class} object representing the class or interface
 175      * that declares the field represented by this {@code Field} object.
 176      */
 177     @Override
 178     public Class<?> getDeclaringClass() {
 179         return clazz;
 180     }
 181 
 182     /**
 183      * Returns the name of the field represented by this {@code Field} object.
 184      */
 185     public String getName() {
 186         return name;
 187     }
 188 
 189     /**
 190      * Returns the Java language modifiers for the field represented
 191      * by this {@code Field} object, as an integer. The {@code Modifier} class should
 192      * be used to decode the modifiers.
 193      *
 194      * @see Modifier
 195      */
 196     public int getModifiers() {
 197         return modifiers;
 198     }
 199 
 200     /**
 201      * Returns {@code true} if this field represents an element of
 202      * an enumerated type; returns {@code false} otherwise.
 203      *
 204      * @return {@code true} if and only if this field represents an element of
 205      * an enumerated type.
 206      * @since 1.5
 207      */
 208     public boolean isEnumConstant() {
 209         return (getModifiers() & Modifier.ENUM) != 0;
 210     }
 211 
 212     /**
 213      * Returns {@code true} if this field is a synthetic
 214      * field; returns {@code false} otherwise.
 215      *
 216      * @return true if and only if this field is a synthetic
 217      * field as defined by the Java Language Specification.
 218      * @since 1.5
 219      */
 220     public boolean isSynthetic() {
 221         return Modifier.isSynthetic(getModifiers());
 222     }
 223 
 224     /**
 225      * Returns a {@code Class} object that identifies the
 226      * declared type for the field represented by this
 227      * {@code Field} object.
 228      *
 229      * @return a {@code Class} object identifying the declared
 230      * type of the field represented by this object
 231      */
 232     public Class<?> getType() {
 233         return type;
 234     }
 235 
 236     /**
 237      * Returns a {@code Type} object that represents the declared type for
 238      * the field represented by this {@code Field} object.
 239      *
 240      * <p>If the {@code Type} is a parameterized type, the
 241      * {@code Type} object returned must accurately reflect the
 242      * actual type parameters used in the source code.
 243      *
 244      * <p>If the type of the underlying field is a type variable or a
 245      * parameterized type, it is created. Otherwise, it is resolved.
 246      *
 247      * @return a {@code Type} object that represents the declared type for
 248      *     the field represented by this {@code Field} object
 249      * @throws GenericSignatureFormatError if the generic field
 250      *     signature does not conform to the format specified in
 251      *     <cite>The Java&trade; Virtual Machine Specification</cite>
 252      * @throws TypeNotPresentException if the generic type
 253      *     signature of the underlying field refers to a non-existent
 254      *     type declaration
 255      * @throws MalformedParameterizedTypeException if the generic
 256      *     signature of the underlying field refers to a parameterized type
 257      *     that cannot be instantiated for any reason
 258      * @since 1.5
 259      */
 260     public Type getGenericType() {
 261         if (getGenericSignature() != null)
 262             return getGenericInfo().getGenericType();
 263         else
 264             return getType();
 265     }
 266 
 267 
 268     /**
 269      * Compares this {@code Field} against the specified object.  Returns
 270      * true if the objects are the same.  Two {@code Field} objects are the same if
 271      * they were declared by the same class and have the same name
 272      * and type.
 273      */
 274     public boolean equals(Object obj) {
 275         if (obj != null && obj instanceof Field) {
 276             Field other = (Field)obj;
 277             return (getDeclaringClass() == other.getDeclaringClass())
 278                 && (getName() == other.getName())
 279                 && (getType() == other.getType());
 280         }
 281         return false;
 282     }
 283 
 284     /**
 285      * Returns a hashcode for this {@code Field}.  This is computed as the
 286      * exclusive-or of the hashcodes for the underlying field's
 287      * declaring class name and its name.
 288      */
 289     public int hashCode() {
 290         return getDeclaringClass().getName().hashCode() ^ getName().hashCode();
 291     }
 292 
 293     /**
 294      * Returns a string describing this {@code Field}.  The format is
 295      * the access modifiers for the field, if any, followed
 296      * by the field type, followed by a space, followed by
 297      * the fully-qualified name of the class declaring the field,
 298      * followed by a period, followed by the name of the field.
 299      * For example:
 300      * <pre>
 301      *    public static final int java.lang.Thread.MIN_PRIORITY
 302      *    private int java.io.FileDescriptor.fd
 303      * </pre>
 304      *
 305      * <p>The modifiers are placed in canonical order as specified by
 306      * "The Java Language Specification".  This is {@code public},
 307      * {@code protected} or {@code private} first, and then other
 308      * modifiers in the following order: {@code static}, {@code final},
 309      * {@code transient}, {@code volatile}.
 310      *
 311      * @return a string describing this {@code Field}
 312      * @jls 8.3.1 Field Modifiers
 313      */
 314     public String toString() {
 315         int mod = getModifiers();
 316         return (((mod == 0) ? "" : (Modifier.toString(mod) + " "))
 317             + getType().getTypeName() + " "
 318             + getDeclaringClass().getTypeName() + "."
 319             + getName());
 320     }
 321 
 322     /**
 323      * Returns a string describing this {@code Field}, including
 324      * its generic type.  The format is the access modifiers for the
 325      * field, if any, followed by the generic field type, followed by
 326      * a space, followed by the fully-qualified name of the class
 327      * declaring the field, followed by a period, followed by the name
 328      * of the field.
 329      *
 330      * <p>The modifiers are placed in canonical order as specified by
 331      * "The Java Language Specification".  This is {@code public},
 332      * {@code protected} or {@code private} first, and then other
 333      * modifiers in the following order: {@code static}, {@code final},
 334      * {@code transient}, {@code volatile}.
 335      *
 336      * @return a string describing this {@code Field}, including
 337      * its generic type
 338      *
 339      * @since 1.5
 340      * @jls 8.3.1 Field Modifiers
 341      */
 342     public String toGenericString() {
 343         int mod = getModifiers();
 344         Type fieldType = getGenericType();
 345         return (((mod == 0) ? "" : (Modifier.toString(mod) + " "))
 346             + fieldType.getTypeName() + " "
 347             + getDeclaringClass().getTypeName() + "."
 348             + getName());
 349     }
 350 
 351     /**
 352      * Returns the value of the field represented by this {@code Field}, on
 353      * the specified object. The value is automatically wrapped in an
 354      * object if it has a primitive type.
 355      *
 356      * <p>The underlying field's value is obtained as follows:
 357      *
 358      * <p>If the underlying field is a static field, the {@code obj} argument
 359      * is ignored; it may be null.
 360      *
 361      * <p>Otherwise, the underlying field is an instance field.  If the
 362      * specified {@code obj} argument is null, the method throws a
 363      * {@code NullPointerException}. If the specified object is not an
 364      * instance of the class or interface declaring the underlying
 365      * field, the method throws an {@code IllegalArgumentException}.
 366      *
 367      * <p>If this {@code Field} object is enforcing Java language access control, and
 368      * the underlying field is inaccessible, the method throws an
 369      * {@code IllegalAccessException}.
 370      * If the underlying field is static, the class that declared the
 371      * field is initialized if it has not already been initialized.
 372      *
 373      * <p>Otherwise, the value is retrieved from the underlying instance
 374      * or static field.  If the field has a primitive type, the value
 375      * is wrapped in an object before being returned, otherwise it is
 376      * returned as is.
 377      *
 378      * <p>If the field is hidden in the type of {@code obj},
 379      * the field's value is obtained according to the preceding rules.
 380      *
 381      * @param obj object from which the represented field's value is
 382      * to be extracted
 383      * @return the value of the represented field in object
 384      * {@code obj}; primitive values are wrapped in an appropriate
 385      * object before being returned
 386      *
 387      * @exception IllegalAccessException    if this {@code Field} object
 388      *              is enforcing Java language access control and the underlying
 389      *              field is inaccessible.
 390      * @exception IllegalArgumentException  if the specified object is not an
 391      *              instance of the class or interface declaring the underlying
 392      *              field (or a subclass or implementor thereof).
 393      * @exception NullPointerException      if the specified object is null
 394      *              and the field is an instance field.
 395      * @exception ExceptionInInitializerError if the initialization provoked
 396      *              by this method fails.
 397      */
 398     @CallerSensitive
 399     public Object get(Object obj)
 400         throws IllegalArgumentException, IllegalAccessException
 401     {
 402         if (!override) {
 403             Class<?> caller = Reflection.getCallerClass();
 404             checkAccess(caller, clazz, obj, modifiers);
 405         }
 406         return getFieldAccessor(obj).get(obj);
 407     }
 408 
 409     /**
 410      * Gets the value of a static or instance {@code boolean} field.
 411      *
 412      * @param obj the object to extract the {@code boolean} value
 413      * from
 414      * @return the value of the {@code boolean} field
 415      *
 416      * @exception IllegalAccessException    if this {@code Field} object
 417      *              is enforcing Java language access control and the underlying
 418      *              field is inaccessible.
 419      * @exception IllegalArgumentException  if the specified object is not
 420      *              an instance of the class or interface declaring the
 421      *              underlying field (or a subclass or implementor
 422      *              thereof), or if the field value cannot be
 423      *              converted to the type {@code boolean} by a
 424      *              widening conversion.
 425      * @exception NullPointerException      if the specified object is null
 426      *              and the field is an instance field.
 427      * @exception ExceptionInInitializerError if the initialization provoked
 428      *              by this method fails.
 429      * @see       Field#get
 430      */
 431     @CallerSensitive
 432     public boolean getBoolean(Object obj)
 433         throws IllegalArgumentException, IllegalAccessException
 434     {
 435         if (!override) {
 436             Class<?> caller = Reflection.getCallerClass();
 437             checkAccess(caller, clazz, obj, modifiers);
 438         }
 439         return getFieldAccessor(obj).getBoolean(obj);
 440     }
 441 
 442     /**
 443      * Gets the value of a static or instance {@code byte} field.
 444      *
 445      * @param obj the object to extract the {@code byte} value
 446      * from
 447      * @return the value of the {@code byte} field
 448      *
 449      * @exception IllegalAccessException    if this {@code Field} object
 450      *              is enforcing Java language access control and the underlying
 451      *              field is inaccessible.
 452      * @exception IllegalArgumentException  if the specified object is not
 453      *              an instance of the class or interface declaring the
 454      *              underlying field (or a subclass or implementor
 455      *              thereof), or if the field value cannot be
 456      *              converted to the type {@code byte} by a
 457      *              widening conversion.
 458      * @exception NullPointerException      if the specified object is null
 459      *              and the field is an instance field.
 460      * @exception ExceptionInInitializerError if the initialization provoked
 461      *              by this method fails.
 462      * @see       Field#get
 463      */
 464     @CallerSensitive
 465     public byte getByte(Object obj)
 466         throws IllegalArgumentException, IllegalAccessException
 467     {
 468         if (!override) {
 469             Class<?> caller = Reflection.getCallerClass();
 470             checkAccess(caller, clazz, obj, modifiers);
 471         }
 472         return getFieldAccessor(obj).getByte(obj);
 473     }
 474 
 475     /**
 476      * Gets the value of a static or instance field of type
 477      * {@code char} or of another primitive type convertible to
 478      * type {@code char} via a widening conversion.
 479      *
 480      * @param obj the object to extract the {@code char} value
 481      * from
 482      * @return the value of the field converted to type {@code char}
 483      *
 484      * @exception IllegalAccessException    if this {@code Field} object
 485      *              is enforcing Java language access control and the underlying
 486      *              field is inaccessible.
 487      * @exception IllegalArgumentException  if the specified object is not
 488      *              an instance of the class or interface declaring the
 489      *              underlying field (or a subclass or implementor
 490      *              thereof), or if the field value cannot be
 491      *              converted to the type {@code char} by a
 492      *              widening conversion.
 493      * @exception NullPointerException      if the specified object is null
 494      *              and the field is an instance field.
 495      * @exception ExceptionInInitializerError if the initialization provoked
 496      *              by this method fails.
 497      * @see Field#get
 498      */
 499     @CallerSensitive
 500     public char getChar(Object obj)
 501         throws IllegalArgumentException, IllegalAccessException
 502     {
 503         if (!override) {
 504             Class<?> caller = Reflection.getCallerClass();
 505             checkAccess(caller, clazz, obj, modifiers);
 506         }
 507         return getFieldAccessor(obj).getChar(obj);
 508     }
 509 
 510     /**
 511      * Gets the value of a static or instance field of type
 512      * {@code short} or of another primitive type convertible to
 513      * type {@code short} via a widening conversion.
 514      *
 515      * @param obj the object to extract the {@code short} value
 516      * from
 517      * @return the value of the field converted to type {@code short}
 518      *
 519      * @exception IllegalAccessException    if this {@code Field} object
 520      *              is enforcing Java language access control and the underlying
 521      *              field is inaccessible.
 522      * @exception IllegalArgumentException  if the specified object is not
 523      *              an instance of the class or interface declaring the
 524      *              underlying field (or a subclass or implementor
 525      *              thereof), or if the field value cannot be
 526      *              converted to the type {@code short} by a
 527      *              widening conversion.
 528      * @exception NullPointerException      if the specified object is null
 529      *              and the field is an instance field.
 530      * @exception ExceptionInInitializerError if the initialization provoked
 531      *              by this method fails.
 532      * @see       Field#get
 533      */
 534     @CallerSensitive
 535     public short getShort(Object obj)
 536         throws IllegalArgumentException, IllegalAccessException
 537     {
 538         if (!override) {
 539             Class<?> caller = Reflection.getCallerClass();
 540             checkAccess(caller, clazz, obj, modifiers);
 541         }
 542         return getFieldAccessor(obj).getShort(obj);
 543     }
 544 
 545     /**
 546      * Gets the value of a static or instance field of type
 547      * {@code int} or of another primitive type convertible to
 548      * type {@code int} via a widening conversion.
 549      *
 550      * @param obj the object to extract the {@code int} value
 551      * from
 552      * @return the value of the field converted to type {@code int}
 553      *
 554      * @exception IllegalAccessException    if this {@code Field} object
 555      *              is enforcing Java language access control and the underlying
 556      *              field is inaccessible.
 557      * @exception IllegalArgumentException  if the specified object is not
 558      *              an instance of the class or interface declaring the
 559      *              underlying field (or a subclass or implementor
 560      *              thereof), or if the field value cannot be
 561      *              converted to the type {@code int} by a
 562      *              widening conversion.
 563      * @exception NullPointerException      if the specified object is null
 564      *              and the field is an instance field.
 565      * @exception ExceptionInInitializerError if the initialization provoked
 566      *              by this method fails.
 567      * @see       Field#get
 568      */
 569     @CallerSensitive
 570     public int getInt(Object obj)
 571         throws IllegalArgumentException, IllegalAccessException
 572     {
 573         if (!override) {
 574             Class<?> caller = Reflection.getCallerClass();
 575             checkAccess(caller, clazz, obj, modifiers);
 576         }
 577         return getFieldAccessor(obj).getInt(obj);
 578     }
 579 
 580     /**
 581      * Gets the value of a static or instance field of type
 582      * {@code long} or of another primitive type convertible to
 583      * type {@code long} via a widening conversion.
 584      *
 585      * @param obj the object to extract the {@code long} value
 586      * from
 587      * @return the value of the field converted to type {@code long}
 588      *
 589      * @exception IllegalAccessException    if this {@code Field} object
 590      *              is enforcing Java language access control and the underlying
 591      *              field is inaccessible.
 592      * @exception IllegalArgumentException  if the specified object is not
 593      *              an instance of the class or interface declaring the
 594      *              underlying field (or a subclass or implementor
 595      *              thereof), or if the field value cannot be
 596      *              converted to the type {@code long} by a
 597      *              widening conversion.
 598      * @exception NullPointerException      if the specified object is null
 599      *              and the field is an instance field.
 600      * @exception ExceptionInInitializerError if the initialization provoked
 601      *              by this method fails.
 602      * @see       Field#get
 603      */
 604     @CallerSensitive
 605     public long getLong(Object obj)
 606         throws IllegalArgumentException, IllegalAccessException
 607     {
 608         if (!override) {
 609             Class<?> caller = Reflection.getCallerClass();
 610             checkAccess(caller, clazz, obj, modifiers);
 611         }
 612         return getFieldAccessor(obj).getLong(obj);
 613     }
 614 
 615     /**
 616      * Gets the value of a static or instance field of type
 617      * {@code float} or of another primitive type convertible to
 618      * type {@code float} via a widening conversion.
 619      *
 620      * @param obj the object to extract the {@code float} value
 621      * from
 622      * @return the value of the field converted to type {@code float}
 623      *
 624      * @exception IllegalAccessException    if this {@code Field} object
 625      *              is enforcing Java language access control and the underlying
 626      *              field is inaccessible.
 627      * @exception IllegalArgumentException  if the specified object is not
 628      *              an instance of the class or interface declaring the
 629      *              underlying field (or a subclass or implementor
 630      *              thereof), or if the field value cannot be
 631      *              converted to the type {@code float} by a
 632      *              widening conversion.
 633      * @exception NullPointerException      if the specified object is null
 634      *              and the field is an instance field.
 635      * @exception ExceptionInInitializerError if the initialization provoked
 636      *              by this method fails.
 637      * @see Field#get
 638      */
 639     @CallerSensitive
 640     public float getFloat(Object obj)
 641         throws IllegalArgumentException, IllegalAccessException
 642     {
 643         if (!override) {
 644             Class<?> caller = Reflection.getCallerClass();
 645             checkAccess(caller, clazz, obj, modifiers);
 646         }
 647         return getFieldAccessor(obj).getFloat(obj);
 648     }
 649 
 650     /**
 651      * Gets the value of a static or instance field of type
 652      * {@code double} or of another primitive type convertible to
 653      * type {@code double} via a widening conversion.
 654      *
 655      * @param obj the object to extract the {@code double} value
 656      * from
 657      * @return the value of the field converted to type {@code double}
 658      *
 659      * @exception IllegalAccessException    if this {@code Field} object
 660      *              is enforcing Java language access control and the underlying
 661      *              field is inaccessible.
 662      * @exception IllegalArgumentException  if the specified object is not
 663      *              an instance of the class or interface declaring the
 664      *              underlying field (or a subclass or implementor
 665      *              thereof), or if the field value cannot be
 666      *              converted to the type {@code double} by a
 667      *              widening conversion.
 668      * @exception NullPointerException      if the specified object is null
 669      *              and the field is an instance field.
 670      * @exception ExceptionInInitializerError if the initialization provoked
 671      *              by this method fails.
 672      * @see       Field#get
 673      */
 674     @CallerSensitive
 675     public double getDouble(Object obj)
 676         throws IllegalArgumentException, IllegalAccessException
 677     {
 678         if (!override) {
 679             Class<?> caller = Reflection.getCallerClass();
 680             checkAccess(caller, clazz, obj, modifiers);
 681         }
 682         return getFieldAccessor(obj).getDouble(obj);
 683     }
 684 
 685     /**
 686      * Sets the field represented by this {@code Field} object on the
 687      * specified object argument to the specified new value. The new
 688      * value is automatically unwrapped if the underlying field has a
 689      * primitive type.
 690      *
 691      * <p>The operation proceeds as follows:
 692      *
 693      * <p>If the underlying field is static, the {@code obj} argument is
 694      * ignored; it may be null.
 695      *
 696      * <p>Otherwise the underlying field is an instance field.  If the
 697      * specified object argument is null, the method throws a
 698      * {@code NullPointerException}.  If the specified object argument is not
 699      * an instance of the class or interface declaring the underlying
 700      * field, the method throws an {@code IllegalArgumentException}.
 701      *
 702      * <p>If this {@code Field} object is enforcing Java language access control, and
 703      * the underlying field is inaccessible, the method throws an
 704      * {@code IllegalAccessException}.
 705      *
 706      * <p>If the underlying field is final, the method throws an
 707      * {@code IllegalAccessException} unless {@code setAccessible(true)}
 708      * has succeeded for this {@code Field} object
 709      * and the field is non-static. Setting a final field in this way
 710      * is meaningful only during deserialization or reconstruction of
 711      * instances of classes with blank final fields, before they are
 712      * made available for access by other parts of a program. Use in
 713      * any other context may have unpredictable effects, including cases
 714      * in which other parts of a program continue to use the original
 715      * value of this field.
 716      *
 717      * <p>If the underlying field is of a primitive type, an unwrapping
 718      * conversion is attempted to convert the new value to a value of
 719      * a primitive type.  If this attempt fails, the method throws an
 720      * {@code IllegalArgumentException}.
 721      *
 722      * <p>If, after possible unwrapping, the new value cannot be
 723      * converted to the type of the underlying field by an identity or
 724      * widening conversion, the method throws an
 725      * {@code IllegalArgumentException}.
 726      *
 727      * <p>If the underlying field is static, the class that declared the
 728      * field is initialized if it has not already been initialized.
 729      *
 730      * <p>The field is set to the possibly unwrapped and widened new value.
 731      *
 732      * <p>If the field is hidden in the type of {@code obj},
 733      * the field's value is set according to the preceding rules.
 734      *
 735      * @param obj the object whose field should be modified
 736      * @param value the new value for the field of {@code obj}
 737      * being modified
 738      *
 739      * @exception IllegalAccessException    if this {@code Field} object
 740      *              is enforcing Java language access control and the underlying
 741      *              field is either inaccessible or final.
 742      * @exception IllegalArgumentException  if the specified object is not an
 743      *              instance of the class or interface declaring the underlying
 744      *              field (or a subclass or implementor thereof),
 745      *              or if an unwrapping conversion fails.
 746      * @exception NullPointerException      if the specified object is null
 747      *              and the field is an instance field.
 748      * @exception ExceptionInInitializerError if the initialization provoked
 749      *              by this method fails.
 750      */
 751     @CallerSensitive
 752     public void set(Object obj, Object value)
 753         throws IllegalArgumentException, IllegalAccessException
 754     {
 755         if (!override) {
 756             Class<?> caller = Reflection.getCallerClass();
 757             checkAccess(caller, clazz, obj, modifiers);
 758         }
 759         getFieldAccessor(obj).set(obj, value);
 760     }
 761 
 762     /**
 763      * Sets the value of a field as a {@code boolean} on the specified object.
 764      * This method is equivalent to
 765      * {@code set(obj, zObj)},
 766      * where {@code zObj} is a {@code Boolean} object and
 767      * {@code zObj.booleanValue() == z}.
 768      *
 769      * @param obj the object whose field should be modified
 770      * @param z   the new value for the field of {@code obj}
 771      * being modified
 772      *
 773      * @exception IllegalAccessException    if this {@code Field} object
 774      *              is enforcing Java language access control and the underlying
 775      *              field is either inaccessible or final.
 776      * @exception IllegalArgumentException  if the specified object is not an
 777      *              instance of the class or interface declaring the underlying
 778      *              field (or a subclass or implementor thereof),
 779      *              or if an unwrapping conversion fails.
 780      * @exception NullPointerException      if the specified object is null
 781      *              and the field is an instance field.
 782      * @exception ExceptionInInitializerError if the initialization provoked
 783      *              by this method fails.
 784      * @see       Field#set
 785      */
 786     @CallerSensitive
 787     public void setBoolean(Object obj, boolean z)
 788         throws IllegalArgumentException, IllegalAccessException
 789     {
 790         if (!override) {
 791             Class<?> caller = Reflection.getCallerClass();
 792             checkAccess(caller, clazz, obj, modifiers);
 793         }
 794         getFieldAccessor(obj).setBoolean(obj, z);
 795     }
 796 
 797     /**
 798      * Sets the value of a field as a {@code byte} on the specified object.
 799      * This method is equivalent to
 800      * {@code set(obj, bObj)},
 801      * where {@code bObj} is a {@code Byte} object and
 802      * {@code bObj.byteValue() == b}.
 803      *
 804      * @param obj the object whose field should be modified
 805      * @param b   the new value for the field of {@code obj}
 806      * being modified
 807      *
 808      * @exception IllegalAccessException    if this {@code Field} object
 809      *              is enforcing Java language access control and the underlying
 810      *              field is either inaccessible or final.
 811      * @exception IllegalArgumentException  if the specified object is not an
 812      *              instance of the class or interface declaring the underlying
 813      *              field (or a subclass or implementor thereof),
 814      *              or if an unwrapping conversion fails.
 815      * @exception NullPointerException      if the specified object is null
 816      *              and the field is an instance field.
 817      * @exception ExceptionInInitializerError if the initialization provoked
 818      *              by this method fails.
 819      * @see       Field#set
 820      */
 821     @CallerSensitive
 822     public void setByte(Object obj, byte b)
 823         throws IllegalArgumentException, IllegalAccessException
 824     {
 825         if (!override) {
 826             Class<?> caller = Reflection.getCallerClass();
 827             checkAccess(caller, clazz, obj, modifiers);
 828         }
 829         getFieldAccessor(obj).setByte(obj, b);
 830     }
 831 
 832     /**
 833      * Sets the value of a field as a {@code char} on the specified object.
 834      * This method is equivalent to
 835      * {@code set(obj, cObj)},
 836      * where {@code cObj} is a {@code Character} object and
 837      * {@code cObj.charValue() == c}.
 838      *
 839      * @param obj the object whose field should be modified
 840      * @param c   the new value for the field of {@code obj}
 841      * being modified
 842      *
 843      * @exception IllegalAccessException    if this {@code Field} object
 844      *              is enforcing Java language access control and the underlying
 845      *              field is either inaccessible or final.
 846      * @exception IllegalArgumentException  if the specified object is not an
 847      *              instance of the class or interface declaring the underlying
 848      *              field (or a subclass or implementor thereof),
 849      *              or if an unwrapping conversion fails.
 850      * @exception NullPointerException      if the specified object is null
 851      *              and the field is an instance field.
 852      * @exception ExceptionInInitializerError if the initialization provoked
 853      *              by this method fails.
 854      * @see       Field#set
 855      */
 856     @CallerSensitive
 857     public void setChar(Object obj, char c)
 858         throws IllegalArgumentException, IllegalAccessException
 859     {
 860         if (!override) {
 861             Class<?> caller = Reflection.getCallerClass();
 862             checkAccess(caller, clazz, obj, modifiers);
 863         }
 864         getFieldAccessor(obj).setChar(obj, c);
 865     }
 866 
 867     /**
 868      * Sets the value of a field as a {@code short} on the specified object.
 869      * This method is equivalent to
 870      * {@code set(obj, sObj)},
 871      * where {@code sObj} is a {@code Short} object and
 872      * {@code sObj.shortValue() == s}.
 873      *
 874      * @param obj the object whose field should be modified
 875      * @param s   the new value for the field of {@code obj}
 876      * being modified
 877      *
 878      * @exception IllegalAccessException    if this {@code Field} object
 879      *              is enforcing Java language access control and the underlying
 880      *              field is either inaccessible or final.
 881      * @exception IllegalArgumentException  if the specified object is not an
 882      *              instance of the class or interface declaring the underlying
 883      *              field (or a subclass or implementor thereof),
 884      *              or if an unwrapping conversion fails.
 885      * @exception NullPointerException      if the specified object is null
 886      *              and the field is an instance field.
 887      * @exception ExceptionInInitializerError if the initialization provoked
 888      *              by this method fails.
 889      * @see       Field#set
 890      */
 891     @CallerSensitive
 892     public void setShort(Object obj, short s)
 893         throws IllegalArgumentException, IllegalAccessException
 894     {
 895         if (!override) {
 896             Class<?> caller = Reflection.getCallerClass();
 897             checkAccess(caller, clazz, obj, modifiers);
 898         }
 899         getFieldAccessor(obj).setShort(obj, s);
 900     }
 901 
 902     /**
 903      * Sets the value of a field as an {@code int} on the specified object.
 904      * This method is equivalent to
 905      * {@code set(obj, iObj)},
 906      * where {@code iObj} is an {@code Integer} object and
 907      * {@code iObj.intValue() == i}.
 908      *
 909      * @param obj the object whose field should be modified
 910      * @param i   the new value for the field of {@code obj}
 911      * being modified
 912      *
 913      * @exception IllegalAccessException    if this {@code Field} object
 914      *              is enforcing Java language access control and the underlying
 915      *              field is either inaccessible or final.
 916      * @exception IllegalArgumentException  if the specified object is not an
 917      *              instance of the class or interface declaring the underlying
 918      *              field (or a subclass or implementor thereof),
 919      *              or if an unwrapping conversion fails.
 920      * @exception NullPointerException      if the specified object is null
 921      *              and the field is an instance field.
 922      * @exception ExceptionInInitializerError if the initialization provoked
 923      *              by this method fails.
 924      * @see       Field#set
 925      */
 926     @CallerSensitive
 927     public void setInt(Object obj, int i)
 928         throws IllegalArgumentException, IllegalAccessException
 929     {
 930         if (!override) {
 931             Class<?> caller = Reflection.getCallerClass();
 932             checkAccess(caller, clazz, obj, modifiers);
 933         }
 934         getFieldAccessor(obj).setInt(obj, i);
 935     }
 936 
 937     /**
 938      * Sets the value of a field as a {@code long} on the specified object.
 939      * This method is equivalent to
 940      * {@code set(obj, lObj)},
 941      * where {@code lObj} is a {@code Long} object and
 942      * {@code lObj.longValue() == l}.
 943      *
 944      * @param obj the object whose field should be modified
 945      * @param l   the new value for the field of {@code obj}
 946      * being modified
 947      *
 948      * @exception IllegalAccessException    if this {@code Field} object
 949      *              is enforcing Java language access control and the underlying
 950      *              field is either inaccessible or final.
 951      * @exception IllegalArgumentException  if the specified object is not an
 952      *              instance of the class or interface declaring the underlying
 953      *              field (or a subclass or implementor thereof),
 954      *              or if an unwrapping conversion fails.
 955      * @exception NullPointerException      if the specified object is null
 956      *              and the field is an instance field.
 957      * @exception ExceptionInInitializerError if the initialization provoked
 958      *              by this method fails.
 959      * @see       Field#set
 960      */
 961     @CallerSensitive
 962     public void setLong(Object obj, long l)
 963         throws IllegalArgumentException, IllegalAccessException
 964     {
 965         if (!override) {
 966             Class<?> caller = Reflection.getCallerClass();
 967             checkAccess(caller, clazz, obj, modifiers);
 968         }
 969         getFieldAccessor(obj).setLong(obj, l);
 970     }
 971 
 972     /**
 973      * Sets the value of a field as a {@code float} on the specified object.
 974      * This method is equivalent to
 975      * {@code set(obj, fObj)},
 976      * where {@code fObj} is a {@code Float} object and
 977      * {@code fObj.floatValue() == f}.
 978      *
 979      * @param obj the object whose field should be modified
 980      * @param f   the new value for the field of {@code obj}
 981      * being modified
 982      *
 983      * @exception IllegalAccessException    if this {@code Field} object
 984      *              is enforcing Java language access control and the underlying
 985      *              field is either inaccessible or final.
 986      * @exception IllegalArgumentException  if the specified object is not an
 987      *              instance of the class or interface declaring the underlying
 988      *              field (or a subclass or implementor thereof),
 989      *              or if an unwrapping conversion fails.
 990      * @exception NullPointerException      if the specified object is null
 991      *              and the field is an instance field.
 992      * @exception ExceptionInInitializerError if the initialization provoked
 993      *              by this method fails.
 994      * @see       Field#set
 995      */
 996     @CallerSensitive
 997     public void setFloat(Object obj, float f)
 998         throws IllegalArgumentException, IllegalAccessException
 999     {
1000         if (!override) {
1001             Class<?> caller = Reflection.getCallerClass();
1002             checkAccess(caller, clazz, obj, modifiers);
1003         }
1004         getFieldAccessor(obj).setFloat(obj, f);
1005     }
1006 
1007     /**
1008      * Sets the value of a field as a {@code double} on the specified object.
1009      * This method is equivalent to
1010      * {@code set(obj, dObj)},
1011      * where {@code dObj} is a {@code Double} object and
1012      * {@code dObj.doubleValue() == d}.
1013      *
1014      * @param obj the object whose field should be modified
1015      * @param d   the new value for the field of {@code obj}
1016      * being modified
1017      *
1018      * @exception IllegalAccessException    if this {@code Field} object
1019      *              is enforcing Java language access control and the underlying
1020      *              field is either inaccessible or final.
1021      * @exception IllegalArgumentException  if the specified object is not an
1022      *              instance of the class or interface declaring the underlying
1023      *              field (or a subclass or implementor thereof),
1024      *              or if an unwrapping conversion fails.
1025      * @exception NullPointerException      if the specified object is null
1026      *              and the field is an instance field.
1027      * @exception ExceptionInInitializerError if the initialization provoked
1028      *              by this method fails.
1029      * @see       Field#set
1030      */
1031     @CallerSensitive
1032     public void setDouble(Object obj, double d)
1033         throws IllegalArgumentException, IllegalAccessException
1034     {
1035         if (!override) {
1036             Class<?> caller = Reflection.getCallerClass();
1037             checkAccess(caller, clazz, obj, modifiers);
1038         }
1039         getFieldAccessor(obj).setDouble(obj, d);
1040     }
1041 
1042     // security check is done before calling this method
1043     private FieldAccessor getFieldAccessor(Object obj)
1044         throws IllegalAccessException
1045     {
1046         boolean ov = override;
1047         FieldAccessor a = (ov) ? overrideFieldAccessor : fieldAccessor;
1048         return (a != null) ? a : acquireFieldAccessor(ov);
1049     }
1050 
1051     // NOTE that there is no synchronization used here. It is correct
1052     // (though not efficient) to generate more than one FieldAccessor
1053     // for a given Field. However, avoiding synchronization will
1054     // probably make the implementation more scalable.
1055     private FieldAccessor acquireFieldAccessor(boolean overrideFinalCheck) {
1056         // First check to see if one has been created yet, and take it
1057         // if so
1058         FieldAccessor tmp = null;
1059         if (root != null) tmp = root.getFieldAccessor(overrideFinalCheck);
1060         if (tmp != null) {
1061             if (overrideFinalCheck)
1062                 overrideFieldAccessor = tmp;
1063             else
1064                 fieldAccessor = tmp;
1065         } else {
1066             // Otherwise fabricate one and propagate it up to the root
1067             tmp = reflectionFactory.newFieldAccessor(this, overrideFinalCheck);
1068             setFieldAccessor(tmp, overrideFinalCheck);
1069         }
1070 
1071         return tmp;
1072     }
1073 
1074     // Returns FieldAccessor for this Field object, not looking up
1075     // the chain to the root
1076     private FieldAccessor getFieldAccessor(boolean overrideFinalCheck) {
1077         return (overrideFinalCheck)? overrideFieldAccessor : fieldAccessor;
1078     }
1079 
1080     // Sets the FieldAccessor for this Field object and
1081     // (recursively) its root
1082     private void setFieldAccessor(FieldAccessor accessor, boolean overrideFinalCheck) {
1083         if (overrideFinalCheck)
1084             overrideFieldAccessor = accessor;
1085         else
1086             fieldAccessor = accessor;
1087         // Propagate up
1088         if (root != null) {
1089             root.setFieldAccessor(accessor, overrideFinalCheck);
1090         }
1091     }
1092 
1093     /**
1094      * @throws NullPointerException {@inheritDoc}
1095      * @since 1.5
1096      */
1097     public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
1098         Objects.requireNonNull(annotationClass);
1099         return annotationClass.cast(declaredAnnotations().get(annotationClass));
1100     }
1101 
1102     /**
1103      * {@inheritDoc}
1104      * @throws NullPointerException {@inheritDoc}
1105      * @since 1.8
1106      */
1107     @Override
1108     public <T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass) {
1109         Objects.requireNonNull(annotationClass);
1110 
1111         return AnnotationSupport.getDirectlyAndIndirectlyPresent(declaredAnnotations(), annotationClass);
1112     }
1113 
1114     /**
1115      * {@inheritDoc}
1116      */
1117     public Annotation[] getDeclaredAnnotations()  {
1118         return AnnotationParser.toArray(declaredAnnotations());
1119     }
1120 
1121     private transient volatile Map<Class<? extends Annotation>, Annotation> declaredAnnotations;
1122 
1123     private Map<Class<? extends Annotation>, Annotation> declaredAnnotations() {
1124         Map<Class<? extends Annotation>, Annotation> declAnnos;
1125         if ((declAnnos = declaredAnnotations) == null) {
1126             synchronized (this) {
1127                 if ((declAnnos = declaredAnnotations) == null) {
1128                     Field root = this.root;
1129                     if (root != null) {
1130                         declAnnos = root.declaredAnnotations();
1131                     } else {
1132                         declAnnos = AnnotationParser.parseAnnotations(
1133                                 annotations,
1134                                 SharedSecrets.getJavaLangAccess()
1135                                         .getConstantPool(getDeclaringClass()),
1136                                 getDeclaringClass());
1137                     }
1138                     declaredAnnotations = declAnnos;
1139                 }
1140             }
1141         }
1142         return declAnnos;
1143     }
1144 
1145     private native byte[] getTypeAnnotationBytes0();
1146 
1147     /**
1148      * Returns an AnnotatedType object that represents the use of a type to specify
1149      * the declared type of the field represented by this Field.
1150      * @return an object representing the declared type of the field
1151      * represented by this Field
1152      *
1153      * @since 1.8
1154      */
1155     public AnnotatedType getAnnotatedType() {
1156         return TypeAnnotationParser.buildAnnotatedType(getTypeAnnotationBytes0(),
1157                                                        SharedSecrets.getJavaLangAccess().
1158                                                            getConstantPool(getDeclaringClass()),
1159                                                        this,
1160                                                        getDeclaringClass(),
1161                                                        getGenericType(),
1162                                                        TypeAnnotation.TypeAnnotationTarget.FIELD);
1163 }
1164 }