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