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