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