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