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