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