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 java.lang.annotation.Annotation;
29 import java.net.URL;
30 import java.security.CodeSource;
31 import java.util.Map;
32 import java.util.Set;
33 import java.util.Objects;
34 import jdk.internal.access.SharedSecrets;
35 import jdk.internal.event.FinalFieldMutationEvent;
36 import jdk.internal.loader.ClassLoaders;
37 import jdk.internal.misc.VM;
38 import jdk.internal.module.ModuleBootstrap;
39 import jdk.internal.module.Modules;
40 import jdk.internal.reflect.CallerSensitive;
41 import jdk.internal.reflect.FieldAccessor;
42 import jdk.internal.reflect.Reflection;
43 import jdk.internal.vm.annotation.ForceInline;
44 import jdk.internal.vm.annotation.Stable;
45 import sun.reflect.generics.repository.FieldRepository;
46 import sun.reflect.generics.factory.CoreReflectionFactory;
47 import sun.reflect.generics.factory.GenericsFactory;
48 import sun.reflect.generics.scope.ClassScope;
49 import sun.reflect.annotation.AnnotationParser;
50 import sun.reflect.annotation.AnnotationSupport;
51 import sun.reflect.annotation.TypeAnnotation;
52 import sun.reflect.annotation.TypeAnnotationParser;
53
54 /**
55 * A {@code Field} provides information about, and dynamic access to, a
56 * single field of a class or an interface. The reflected field may
57 * be a class (static) field or an instance field.
58 *
59 * <p>A {@code Field} permits widening conversions to occur during a get or
60 * set access operation, but throws an {@code IllegalArgumentException} if a
61 * narrowing conversion would occur.
62 *
63 * @see Member
64 * @see java.lang.Class
65 * @see java.lang.Class#getFields()
66 * @see java.lang.Class#getField(String)
67 * @see java.lang.Class#getDeclaredFields()
68 * @see java.lang.Class#getDeclaredField(String)
69 *
70 * @author Kenneth Russell
71 * @author Nakul Saraiya
72 * @since 1.1
73 */
74 public final
75 class Field extends AccessibleObject implements Member {
76 private final Class<?> clazz;
77 private final int slot;
78 // This is guaranteed to be interned by the VM in the 1.4
79 // reflection implementation
80 private final String name;
81 private final Class<?> type;
82 private final int modifiers;
83 private final int flags;
84 // Generics and annotations support
85 private final transient String signature;
86 private final byte[] annotations;
87
88 /**
89 * Fields are mutable due to {@link AccessibleObject#setAccessible(boolean)}.
90 * Thus, we return a new copy of a root each time a field is returned.
91 * Some lazily initialized immutable states can be stored on root and shared to the copies.
92 */
93 private Field root;
94 private transient volatile FieldRepository genericInfo;
95 private @Stable FieldAccessor fieldAccessor; // access control enabled
96 private @Stable FieldAccessor overrideFieldAccessor; // access control suppressed
97 // End shared states
98
99 // Generics infrastructure
100
101 private String getGenericSignature() {return signature;}
102
103 // Accessor for factory
104 private GenericsFactory getFactory() {
105 Class<?> c = getDeclaringClass();
106 // create scope and factory
107 return CoreReflectionFactory.make(c, ClassScope.make(c));
108 }
109
110 // Accessor for generic info repository
111 private FieldRepository getGenericInfo() {
112 var genericInfo = this.genericInfo;
113 if (genericInfo == null) {
114 var root = this.root;
115 if (root != null) {
116 genericInfo = root.getGenericInfo();
117 } else {
118 genericInfo = FieldRepository.make(getGenericSignature(), getFactory());
119 }
120 this.genericInfo = genericInfo;
121 }
122 return genericInfo;
123 }
124
125 /**
126 * Package-private constructor
127 */
128 @SuppressWarnings("deprecation")
129 Field(Class<?> declaringClass,
130 String name,
131 Class<?> type,
132 int modifiers,
133 int flags,
134 int slot,
135 String signature,
136 byte[] annotations)
137 {
138 this.clazz = declaringClass;
139 this.name = name;
140 this.type = type;
141 this.modifiers = modifiers;
142 this.flags = flags;
143 this.slot = slot;
144 this.signature = signature;
145 this.annotations = annotations;
146 }
147
148 /**
149 * Package-private routine (exposed to java.lang.Class via
150 * ReflectAccess) which returns a copy of this Field. The copy's
151 * "root" field points to this Field.
152 */
153 Field copy() {
154 // This routine enables sharing of FieldAccessor objects
155 // among Field objects which refer to the same underlying
156 // method in the VM. (All of this contortion is only necessary
157 // because of the "accessibility" bit in AccessibleObject,
158 // which implicitly requires that new java.lang.reflect
159 // objects be fabricated for each reflective call on Class
160 // objects.)
161 if (this.root != null)
162 throw new IllegalArgumentException("Can not copy a non-root Field");
163
164 Field res = new Field(clazz, name, type, modifiers, flags, slot, signature, annotations);
165 res.root = this;
166 // Might as well eagerly propagate this if already present
167 res.fieldAccessor = fieldAccessor;
168 res.overrideFieldAccessor = overrideFieldAccessor;
169 res.genericInfo = genericInfo;
170
171 return res;
172 }
173
174 /**
175 * {@inheritDoc}
176 *
177 * <p>If this reflected object represents a non-final field, and this method is
178 * used to enable access, then both <em>{@linkplain #get(Object) read}</em>
179 * and <em>{@linkplain #set(Object, Object) write}</em> access to the field
180 * are enabled.
181 *
182 * <p>If this reflected object represents a <em>non-modifiable</em> final field
183 * then enabling access only enables read access. Any attempt to {@linkplain
184 * #set(Object, Object) set} the field value throws an {@code
185 * IllegalAccessException}. The following fields are non-modifiable:
186 * <ul>
187 * <li>static final fields declared in any class or interface</li>
188 * <li>final fields declared in a {@linkplain Class#isRecord() record}</li>
189 * <li>final fields declared in a {@linkplain Class#isHidden() hidden class}</li>
190 * </ul>
191 * <p>If this reflected object represents a non-static final field in a class that
192 * is not a record class or hidden class, then enabling access will enable read
193 * access. Whether write access is allowed or not is checked when attempting to
194 * {@linkplain #set(Object, Object) set} the field value.
195 *
196 * @throws InaccessibleObjectException {@inheritDoc}
197 */
198 @Override
199 @CallerSensitive
200 public void setAccessible(boolean flag) {
201 if (flag) checkCanSetAccessible(Reflection.getCallerClass());
202 setAccessible0(flag);
203 }
204
205 @Override
206 void checkCanSetAccessible(Class<?> caller) {
207 checkCanSetAccessible(caller, clazz);
208 }
209
210 /**
211 * Returns the {@code Class} object representing the class or interface
212 * that declares the field represented by this {@code Field} object.
213 */
214 @Override
215 public Class<?> getDeclaringClass() {
216 return clazz;
217 }
218
219 /**
220 * Returns the name of the field represented by this {@code Field} object.
221 */
222 public String getName() {
223 return name;
224 }
225
226 /**
227 * Returns the Java language modifiers for the field represented
228 * by this {@code Field} object, as an integer. The {@code Modifier} class should
229 * be used to decode the modifiers.
230 *
231 * @see Modifier
232 * @see #accessFlags()
233 * @jls 8.3 Field Declarations
234 * @jls 9.3 Field (Constant) Declarations
235 */
236 public int getModifiers() {
237 return modifiers;
238 }
239
240 /**
241 * {@return an unmodifiable set of the {@linkplain AccessFlag
242 * access flags} for this field, possibly empty}
243 * The {@code AccessFlags} may depend on the class file format version of the class.
244 *
245 * @see #getModifiers()
246 * @jvms 4.5 Fields
247 * @since 20
248 */
249 @Override
250 public Set<AccessFlag> accessFlags() {
251 return reflectionFactory.parseAccessFlags(getModifiers(), AccessFlag.Location.FIELD, getDeclaringClass());
252 }
253
254 /**
255 * Returns {@code true} if this field represents an element of
256 * an enumerated class; returns {@code false} otherwise.
257 *
258 * @return {@code true} if and only if this field represents an element of
259 * an enumerated class.
260 * @since 1.5
261 * @jls 8.9.1 Enum Constants
262 */
263 public boolean isEnumConstant() {
264 return (getModifiers() & Modifier.ENUM) != 0;
265 }
266
267 /**
268 * Returns {@code true} if this field is a synthetic
269 * field; returns {@code false} otherwise.
270 *
271 * @return true if and only if this field is a synthetic
272 * field as defined by the Java Language Specification.
273 * @since 1.5
274 * @see <a
275 * href="{@docRoot}/java.base/java/lang/reflect/package-summary.html#LanguageJvmModel">Java
276 * programming language and JVM modeling in core reflection</a>
277 */
278 public boolean isSynthetic() {
279 return Modifier.isSynthetic(getModifiers());
280 }
281
282 /**
283 * Returns a {@code Class} object that identifies the
284 * declared type for the field represented by this
285 * {@code Field} object.
286 *
287 * @return a {@code Class} object identifying the declared
288 * type of the field represented by this object
289 */
290 public Class<?> getType() {
291 return type;
292 }
293
294 /**
295 * Returns a {@code Type} object that represents the declared type for
296 * the field represented by this {@code Field} object.
297 *
298 * <p>If the declared type of the field is a parameterized type,
299 * the {@code Type} object returned must accurately reflect the
300 * actual type arguments used in the source code.
301 *
302 * <p>If the type of the underlying field is a type variable or a
303 * parameterized type, it is created. Otherwise, it is resolved.
304 *
305 * @return a {@code Type} object that represents the declared type for
306 * the field represented by this {@code Field} object
307 * @throws GenericSignatureFormatError if the generic field
308 * signature does not conform to the format specified in
309 * <cite>The Java Virtual Machine Specification</cite>
310 * @throws TypeNotPresentException if the generic type
311 * signature of the underlying field refers to a non-existent
312 * class or interface declaration
313 * @throws MalformedParameterizedTypeException if the generic
314 * signature of the underlying field refers to a parameterized type
315 * that cannot be instantiated for any reason
316 * @since 1.5
317 */
318 public Type getGenericType() {
319 if (getGenericSignature() != null)
320 return getGenericInfo().getGenericType();
321 else
322 return getType();
323 }
324
325
326 /**
327 * Compares this {@code Field} against the specified object. Returns
328 * true if the objects are the same. Two {@code Field} objects are the same if
329 * they were declared by the same class and have the same name
330 * and type.
331 */
332 public boolean equals(Object obj) {
333 if (obj instanceof Field other) {
334 return (getDeclaringClass() == other.getDeclaringClass())
335 && (getName() == other.getName())
336 && (getType() == other.getType());
337 }
338 return false;
339 }
340
341 /**
342 * Returns a hashcode for this {@code Field}. This is computed as the
343 * exclusive-or of the hashcodes for the underlying field's
344 * declaring class name and its name.
345 */
346 public int hashCode() {
347 return getDeclaringClass().getName().hashCode() ^ getName().hashCode();
348 }
349
350 /**
351 * Returns a string describing this {@code Field}. The format is
352 * the access modifiers for the field, if any, followed
353 * by the field type, followed by a space, followed by
354 * the fully-qualified name of the class declaring the field,
355 * followed by a period, followed by the name of the field.
356 * For example:
357 * <pre>
358 * public static final int java.lang.Thread.MIN_PRIORITY
359 * private int java.io.FileDescriptor.fd
360 * </pre>
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}
369 * @jls 8.3.1 Field Modifiers
370 */
371 public String toString() {
372 int mod = getModifiers() & Modifier.fieldModifiers();
373 return (((mod == 0) ? "" : (Modifier.toString(mod) + " "))
374 + getType().getTypeName() + " "
375 + getDeclaringClass().getTypeName() + "."
376 + getName());
377 }
378
379 @Override
380 String toShortString() {
381 return "field " + getDeclaringClass().getTypeName() + "." + getName();
382 }
383
384 /**
385 * Returns a string describing this {@code Field}, including
386 * its generic type. The format is the access modifiers for the
387 * field, if any, followed by the generic field type, followed by
388 * a space, followed by the fully-qualified name of the class
389 * declaring the field, followed by a period, followed by the name
390 * of the field.
391 *
392 * <p>The modifiers are placed in canonical order as specified by
393 * "The Java Language Specification". This is {@code public},
394 * {@code protected} or {@code private} first, and then other
395 * modifiers in the following order: {@code static}, {@code final},
396 * {@code transient}, {@code volatile}.
397 *
398 * @return a string describing this {@code Field}, including
399 * its generic type
400 *
401 * @since 1.5
402 * @jls 8.3.1 Field Modifiers
403 */
404 public String toGenericString() {
405 int mod = getModifiers() & Modifier.fieldModifiers();
406 Type fieldType = getGenericType();
407 return (((mod == 0) ? "" : (Modifier.toString(mod) + " "))
408 + fieldType.getTypeName() + " "
409 + getDeclaringClass().getTypeName() + "."
410 + getName());
411 }
412
413 /**
414 * Returns the value of the field represented by this {@code Field}, on
415 * the specified object. The value is automatically wrapped in an
416 * object if it has a primitive type.
417 *
418 * <p>The underlying field's value is obtained as follows:
419 *
420 * <p>If the underlying field is a static field, the {@code obj} argument
421 * is ignored; it may be null.
422 *
423 * <p>Otherwise, the underlying field is an instance field. If the
424 * specified {@code obj} argument is null, the method throws a
425 * {@code NullPointerException}. If the specified object is not an
426 * instance of the class or interface declaring the underlying
427 * field, the method throws an {@code IllegalArgumentException}.
428 *
429 * <p>If this {@code Field} object is enforcing Java language access control, and
430 * the underlying field is inaccessible, the method throws an
431 * {@code IllegalAccessException}.
432 * If the underlying field is static, the class that declared the
433 * field is initialized if it has not already been initialized.
434 *
435 * <p>Otherwise, the value is retrieved from the underlying instance
436 * or static field. If the field has a primitive type, the value
437 * is wrapped in an object before being returned, otherwise it is
438 * returned as is.
439 *
440 * <p>If the field is hidden in the type of {@code obj},
441 * the field's value is obtained according to the preceding rules.
442 *
443 * @param obj object from which the represented field's value is
444 * to be extracted
445 * @return the value of the represented field in object
446 * {@code obj}; primitive values are wrapped in an appropriate
447 * object before being returned
448 *
449 * @throws IllegalAccessException if this {@code Field} object
450 * is enforcing Java language access control and the underlying
451 * field is inaccessible.
452 * @throws IllegalArgumentException if the specified object is not an
453 * instance of the class or interface declaring the underlying
454 * field (or a subclass or implementor thereof).
455 * @throws NullPointerException if the specified object is null
456 * and the field is an instance field.
457 * @throws ExceptionInInitializerError if the initialization provoked
458 * by this method fails.
459 */
460 @CallerSensitive
461 @ForceInline // to ensure Reflection.getCallerClass optimization
462 public Object get(Object obj)
463 throws IllegalArgumentException, IllegalAccessException
464 {
465 if (!override) {
466 Class<?> caller = Reflection.getCallerClass();
467 checkAccess(caller, obj);
468 return getFieldAccessor().get(obj);
469 } else {
470 return getOverrideFieldAccessor().get(obj);
471 }
472 }
473
474 /**
475 * Gets the value of a static or instance {@code boolean} field.
476 *
477 * @param obj the object to extract the {@code boolean} value
478 * from
479 * @return the value of the {@code boolean} field
480 *
481 * @throws IllegalAccessException if this {@code Field} object
482 * is enforcing Java language access control and the underlying
483 * field is inaccessible.
484 * @throws IllegalArgumentException if the specified object is not
485 * an instance of the class or interface declaring the
486 * underlying field (or a subclass or implementor
487 * thereof), or if the field value cannot be
488 * converted to the type {@code boolean} by a
489 * widening conversion.
490 * @throws NullPointerException if the specified object is null
491 * and the field is an instance field.
492 * @throws ExceptionInInitializerError if the initialization provoked
493 * by this method fails.
494 * @see Field#get
495 */
496 @CallerSensitive
497 @ForceInline // to ensure Reflection.getCallerClass optimization
498 public boolean getBoolean(Object obj)
499 throws IllegalArgumentException, IllegalAccessException
500 {
501 if (!override) {
502 Class<?> caller = Reflection.getCallerClass();
503 checkAccess(caller, obj);
504 return getFieldAccessor().getBoolean(obj);
505 } else {
506 return getOverrideFieldAccessor().getBoolean(obj);
507 }
508 }
509
510 /**
511 * Gets the value of a static or instance {@code byte} field.
512 *
513 * @param obj the object to extract the {@code byte} value
514 * from
515 * @return the value of the {@code byte} field
516 *
517 * @throws IllegalAccessException if this {@code Field} object
518 * is enforcing Java language access control and the underlying
519 * field is inaccessible.
520 * @throws IllegalArgumentException if the specified object is not
521 * an instance of the class or interface declaring the
522 * underlying field (or a subclass or implementor
523 * thereof), or if the field value cannot be
524 * converted to the type {@code byte} by a
525 * widening conversion.
526 * @throws NullPointerException if the specified object is null
527 * and the field is an instance field.
528 * @throws ExceptionInInitializerError if the initialization provoked
529 * by this method fails.
530 * @see Field#get
531 */
532 @CallerSensitive
533 @ForceInline // to ensure Reflection.getCallerClass optimization
534 public byte getByte(Object obj)
535 throws IllegalArgumentException, IllegalAccessException
536 {
537 if (!override) {
538 Class<?> caller = Reflection.getCallerClass();
539 checkAccess(caller, obj);
540 return getFieldAccessor().getByte(obj);
541 } else {
542 return getOverrideFieldAccessor().getByte(obj);
543 }
544 }
545
546 /**
547 * Gets the value of a static or instance field of type
548 * {@code char} or of another primitive type convertible to
549 * type {@code char} via a widening conversion.
550 *
551 * @param obj the object to extract the {@code char} value
552 * from
553 * @return the value of the field converted to type {@code char}
554 *
555 * @throws IllegalAccessException if this {@code Field} object
556 * is enforcing Java language access control and the underlying
557 * field is inaccessible.
558 * @throws IllegalArgumentException if the specified object is not
559 * an instance of the class or interface declaring the
560 * underlying field (or a subclass or implementor
561 * thereof), or if the field value cannot be
562 * converted to the type {@code char} by a
563 * widening conversion.
564 * @throws NullPointerException if the specified object is null
565 * and the field is an instance field.
566 * @throws ExceptionInInitializerError if the initialization provoked
567 * by this method fails.
568 * @see Field#get
569 */
570 @CallerSensitive
571 @ForceInline // to ensure Reflection.getCallerClass optimization
572 public char getChar(Object obj)
573 throws IllegalArgumentException, IllegalAccessException
574 {
575 if (!override) {
576 Class<?> caller = Reflection.getCallerClass();
577 checkAccess(caller, obj);
578 return getFieldAccessor().getChar(obj);
579 } else {
580 return getOverrideFieldAccessor().getChar(obj);
581 }
582 }
583
584 /**
585 * Gets the value of a static or instance field of type
586 * {@code short} or of another primitive type convertible to
587 * type {@code short} via a widening conversion.
588 *
589 * @param obj the object to extract the {@code short} value
590 * from
591 * @return the value of the field converted to type {@code short}
592 *
593 * @throws IllegalAccessException if this {@code Field} object
594 * is enforcing Java language access control and the underlying
595 * field is inaccessible.
596 * @throws IllegalArgumentException if the specified object is not
597 * an instance of the class or interface declaring the
598 * underlying field (or a subclass or implementor
599 * thereof), or if the field value cannot be
600 * converted to the type {@code short} by a
601 * widening conversion.
602 * @throws NullPointerException if the specified object is null
603 * and the field is an instance field.
604 * @throws ExceptionInInitializerError if the initialization provoked
605 * by this method fails.
606 * @see Field#get
607 */
608 @CallerSensitive
609 @ForceInline // to ensure Reflection.getCallerClass optimization
610 public short getShort(Object obj)
611 throws IllegalArgumentException, IllegalAccessException
612 {
613 if (!override) {
614 Class<?> caller = Reflection.getCallerClass();
615 checkAccess(caller, obj);
616 return getFieldAccessor().getShort(obj);
617 } else {
618 return getOverrideFieldAccessor().getShort(obj);
619 }
620 }
621
622 /**
623 * Gets the value of a static or instance field of type
624 * {@code int} or of another primitive type convertible to
625 * type {@code int} via a widening conversion.
626 *
627 * @param obj the object to extract the {@code int} value
628 * from
629 * @return the value of the field converted to type {@code int}
630 *
631 * @throws IllegalAccessException if this {@code Field} object
632 * is enforcing Java language access control and the underlying
633 * field is inaccessible.
634 * @throws IllegalArgumentException if the specified object is not
635 * an instance of the class or interface declaring the
636 * underlying field (or a subclass or implementor
637 * thereof), or if the field value cannot be
638 * converted to the type {@code int} by a
639 * widening conversion.
640 * @throws NullPointerException if the specified object is null
641 * and the field is an instance field.
642 * @throws ExceptionInInitializerError if the initialization provoked
643 * by this method fails.
644 * @see Field#get
645 */
646 @CallerSensitive
647 @ForceInline // to ensure Reflection.getCallerClass optimization
648 public int getInt(Object obj)
649 throws IllegalArgumentException, IllegalAccessException
650 {
651 if (!override) {
652 Class<?> caller = Reflection.getCallerClass();
653 checkAccess(caller, obj);
654 return getFieldAccessor().getInt(obj);
655 } else {
656 return getOverrideFieldAccessor().getInt(obj);
657 }
658 }
659
660 /**
661 * Gets the value of a static or instance field of type
662 * {@code long} or of another primitive type convertible to
663 * type {@code long} via a widening conversion.
664 *
665 * @param obj the object to extract the {@code long} value
666 * from
667 * @return the value of the field converted to type {@code long}
668 *
669 * @throws IllegalAccessException if this {@code Field} object
670 * is enforcing Java language access control and the underlying
671 * field is inaccessible.
672 * @throws IllegalArgumentException if the specified object is not
673 * an instance of the class or interface declaring the
674 * underlying field (or a subclass or implementor
675 * thereof), or if the field value cannot be
676 * converted to the type {@code long} by a
677 * widening conversion.
678 * @throws NullPointerException if the specified object is null
679 * and the field is an instance field.
680 * @throws ExceptionInInitializerError if the initialization provoked
681 * by this method fails.
682 * @see Field#get
683 */
684 @CallerSensitive
685 @ForceInline // to ensure Reflection.getCallerClass optimization
686 public long getLong(Object obj)
687 throws IllegalArgumentException, IllegalAccessException
688 {
689 if (!override) {
690 Class<?> caller = Reflection.getCallerClass();
691 checkAccess(caller, obj);
692 return getFieldAccessor().getLong(obj);
693 } else {
694 return getOverrideFieldAccessor().getLong(obj);
695 }
696 }
697
698 /**
699 * Gets the value of a static or instance field of type
700 * {@code float} or of another primitive type convertible to
701 * type {@code float} via a widening conversion.
702 *
703 * @param obj the object to extract the {@code float} value
704 * from
705 * @return the value of the field converted to type {@code float}
706 *
707 * @throws IllegalAccessException if this {@code Field} object
708 * is enforcing Java language access control and the underlying
709 * field is inaccessible.
710 * @throws IllegalArgumentException if the specified object is not
711 * an instance of the class or interface declaring the
712 * underlying field (or a subclass or implementor
713 * thereof), or if the field value cannot be
714 * converted to the type {@code float} by a
715 * widening conversion.
716 * @throws NullPointerException if the specified object is null
717 * and the field is an instance field.
718 * @throws ExceptionInInitializerError if the initialization provoked
719 * by this method fails.
720 * @see Field#get
721 */
722 @CallerSensitive
723 @ForceInline // to ensure Reflection.getCallerClass optimization
724 public float getFloat(Object obj)
725 throws IllegalArgumentException, IllegalAccessException
726 {
727 if (!override) {
728 Class<?> caller = Reflection.getCallerClass();
729 checkAccess(caller, obj);
730 return getFieldAccessor().getFloat(obj);
731 } else {
732 return getOverrideFieldAccessor().getFloat(obj);
733 }
734 }
735
736 /**
737 * Gets the value of a static or instance field of type
738 * {@code double} or of another primitive type convertible to
739 * type {@code double} via a widening conversion.
740 *
741 * @param obj the object to extract the {@code double} value
742 * from
743 * @return the value of the field converted to type {@code double}
744 *
745 * @throws IllegalAccessException if this {@code Field} object
746 * is enforcing Java language access control and the underlying
747 * field is inaccessible.
748 * @throws IllegalArgumentException if the specified object is not
749 * an instance of the class or interface declaring the
750 * underlying field (or a subclass or implementor
751 * thereof), or if the field value cannot be
752 * converted to the type {@code double} by a
753 * widening conversion.
754 * @throws NullPointerException if the specified object is null
755 * and the field is an instance field.
756 * @throws ExceptionInInitializerError if the initialization provoked
757 * by this method fails.
758 * @see Field#get
759 */
760 @CallerSensitive
761 @ForceInline // to ensure Reflection.getCallerClass optimization
762 public double getDouble(Object obj)
763 throws IllegalArgumentException, IllegalAccessException
764 {
765 if (!override) {
766 Class<?> caller = Reflection.getCallerClass();
767 checkAccess(caller, obj);
768 return getFieldAccessor().getDouble(obj);
769 } else {
770 return getOverrideFieldAccessor().getDouble(obj);
771 }
772 }
773
774 /**
775 * Sets the field represented by this {@code Field} object on the
776 * specified object argument to the specified new value. The new
777 * value is automatically unwrapped if the underlying field has a
778 * primitive type.
779 *
780 * <p>The operation proceeds as follows:
781 *
782 * <p>If the underlying field is static, the {@code obj} argument is
783 * ignored; it may be null.
784 *
785 * <p>Otherwise the underlying field is an instance field. If the
786 * specified object argument is null, the method throws a
787 * {@code NullPointerException}. If the specified object argument is not
788 * an instance of the class or interface declaring the underlying
789 * field, the method throws an {@code IllegalArgumentException}.
790 *
791 * <p>If this {@code Field} object is enforcing Java language access control, and
792 * the underlying field is inaccessible, the method throws an
793 * {@code IllegalAccessException}.
794 *
795 * <p>If the underlying field is final, this {@code Field} object has <em>write</em>
796 * access if and only if all of the following conditions are true, where {@code D} is
797 * the field's {@linkplain #getDeclaringClass() declaring class}:
798 *
799 * <ul>
800 * <li>{@link #setAccessible(boolean) setAccessible(true)} has succeeded for this
801 * {@code Field} object.</li>
802 * <li><a href="doc-files/MutationMethods.html">final field mutation is enabled</a>
803 * for the caller's module.</li>
804 * <li> At least one of the following conditions holds:
805 * <ol type="a">
806 * <li> {@code D} and the caller class are in the same module.</li>
807 * <li> The field is {@code public} and {@code D} is {@code public} in a package
808 * that the module containing {@code D} exports to at least the caller's module.</li>
809 * <li> {@code D} is in a package that is {@linkplain Module#isOpen(String, Module)
810 * open} to the caller's module.</li>
811 * </ol>
812 * </li>
813 * <li>{@code D} is not a {@linkplain Class#isRecord() record class}.</li>
814 * <li>{@code D} is not a {@linkplain Class#isHidden() hidden class}.</li>
815 * <li>{@code D} is not a {@linkplain Class#isValue() value class}.</li>
816 * <li>The field is non-static.</li>
817 * </ul>
818 *
819 * <p>If any of the above conditions is not met, this method throws an
820 * {@code IllegalAccessException}.
821 *
822 * <p>These conditions are more restrictive than the conditions specified by {@link
823 * #setAccessible(boolean)} to suppress access checks. In particular, updating a
824 * module to export or open a package cannot be used to allow <em>write</em> access
825 * to final fields with the {@code set} methods defined by {@code Field}.
826 * Condition (b) is not met if the module containing {@code D} has been updated with
827 * {@linkplain Module#addExports(String, Module) addExports} to export the package to
828 * the caller's module. Condition (c) is not met if the module containing {@code D}
829 * has been updated with {@linkplain Module#addOpens(String, Module) addOpens} to open
830 * the package to the caller's module.
831 *
832 * <p>This method may be called by <a href="{@docRoot}/../specs/jni/index.html">
833 * JNI code</a> with no caller class on the stack. In that case, and when the
834 * underlying field is final, this {@code Field} object has <em>write</em> access
835 * if and only if all of the following conditions are true, where {@code D} is the
836 * field's {@linkplain #getDeclaringClass() declaring class}:
837 *
838 * <ul>
839 * <li>{@code setAccessible(true)} has succeeded for this {@code Field} object.</li>
840 * <li>final field mutation is enabled for the unnamed module.</li>
841 * <li>The field is {@code public} and {@code D} is {@code public} in a package that
842 * is {@linkplain Module#isExported(String) exported} to all modules.</li>
843 * <li>{@code D} is not a {@linkplain Class#isRecord() record class}.</li>
844 * <li>{@code D} is not a {@linkplain Class#isHidden() hidden class}.</li>
845 * <li>The field is non-static.</li>
846 * </ul>
847 *
848 * <p>If any of the above conditions is not met, this method throws an
849 * {@code IllegalAccessException}.
850 *
851 * <p> Setting a final field in this way
852 * is meaningful only during deserialization or reconstruction of
853 * instances of classes with blank final fields, before they are
854 * made available for access by other parts of a program. Use in
855 * any other context may have unpredictable effects, including cases
856 * in which other parts of a program continue to use the original
857 * value of this field.
858 *
859 * <p>If the underlying field is of a primitive type, an unwrapping
860 * conversion is attempted to convert the new value to a value of
861 * a primitive type. If this attempt fails, the method throws an
862 * {@code IllegalArgumentException}.
863 *
864 * <p>If, after possible unwrapping, the new value cannot be
865 * converted to the type of the underlying field by an identity or
866 * widening conversion, the method throws an
867 * {@code IllegalArgumentException}.
868 *
869 * <p>If the underlying field is static, the class that declared the
870 * field is initialized if it has not already been initialized.
871 *
872 * <p>The field is set to the possibly unwrapped and widened new value.
873 *
874 * <p>If the field is hidden in the type of {@code obj},
875 * the field's value is set according to the preceding rules.
876 *
877 * @param obj the object whose field should be modified
878 * @param value the new value for the field of {@code obj}
879 * being modified
880 *
881 * @throws IllegalAccessException if this {@code Field} object
882 * is enforcing Java language access control and the underlying
883 * field is inaccessible or final;
884 * or if this {@code Field} object has no write access.
885 * @throws IllegalArgumentException if the specified object is not an
886 * instance of the class or interface declaring the underlying
887 * field (or a subclass or implementor thereof),
888 * or if an unwrapping conversion fails.
889 * @throws NullPointerException if the specified object is null
890 * and the field is an instance field.
891 * @throws ExceptionInInitializerError if the initialization provoked
892 * by this method fails.
893 *
894 * @see <a href="doc-files/MutationMethods.html">Mutation methods</a>
895 */
896 @CallerSensitive
897 @ForceInline // to ensure Reflection.getCallerClass optimization
898 public void set(Object obj, Object value)
899 throws IllegalArgumentException, IllegalAccessException
900 {
901 if (!override) {
902 Class<?> caller = Reflection.getCallerClass();
903 checkAccess(caller, obj);
904 getFieldAccessor().set(obj, value);
905 return;
906 }
907
908 FieldAccessor fa = getOverrideFieldAccessor();
909 if (!Modifier.isFinal(modifiers)) {
910 fa.set(obj, value);
911 } else {
912 setFinal(Reflection.getCallerClass(), obj, () -> fa.set(obj, value));
913 }
914 }
915
916 /**
917 * Sets the value of a field as a {@code boolean} on the specified object.
918 * This method is equivalent to
919 * {@code set(obj, zObj)},
920 * where {@code zObj} is a {@code Boolean} object and
921 * {@code zObj.booleanValue() == z}.
922 *
923 * @param obj the object whose field should be modified
924 * @param z the new value for the field of {@code obj}
925 * being modified
926 *
927 * @throws IllegalAccessException if this {@code Field} object
928 * is enforcing Java language access control and the underlying
929 * field is either inaccessible or final;
930 * or if this {@code Field} object has no write access.
931 * @throws IllegalArgumentException if the specified object is not an
932 * instance of the class or interface declaring the underlying
933 * field (or a subclass or implementor thereof),
934 * or if an unwrapping conversion fails.
935 * @throws NullPointerException if the specified object is null
936 * and the field is an instance field.
937 * @throws ExceptionInInitializerError if the initialization provoked
938 * by this method fails.
939 * @see Field#set
940 */
941 @CallerSensitive
942 @ForceInline // to ensure Reflection.getCallerClass optimization
943 public void setBoolean(Object obj, boolean z)
944 throws IllegalArgumentException, IllegalAccessException
945 {
946 if (!override) {
947 Class<?> caller = Reflection.getCallerClass();
948 checkAccess(caller, obj);
949 getFieldAccessor().setBoolean(obj, z);
950 return;
951 }
952
953 FieldAccessor fa = getOverrideFieldAccessor();
954 if (!Modifier.isFinal(modifiers)) {
955 fa.setBoolean(obj, z);
956 } else {
957 setFinal(Reflection.getCallerClass(), obj, () -> fa.setBoolean(obj, z));
958 }
959 }
960
961 /**
962 * Sets the value of a field as a {@code byte} on the specified object.
963 * This method is equivalent to
964 * {@code set(obj, bObj)},
965 * where {@code bObj} is a {@code Byte} object and
966 * {@code bObj.byteValue() == b}.
967 *
968 * @param obj the object whose field should be modified
969 * @param b the new value for the field of {@code obj}
970 * being modified
971 *
972 * @throws IllegalAccessException if this {@code Field} object
973 * is enforcing Java language access control and the underlying
974 * field is either inaccessible or final;
975 * or if this {@code Field} object has no write access.
976 * @throws IllegalArgumentException if the specified object is not an
977 * instance of the class or interface declaring the underlying
978 * field (or a subclass or implementor thereof),
979 * or if an unwrapping conversion fails.
980 * @throws NullPointerException if the specified object is null
981 * and the field is an instance field.
982 * @throws ExceptionInInitializerError if the initialization provoked
983 * by this method fails.
984 * @see Field#set
985 */
986 @CallerSensitive
987 @ForceInline // to ensure Reflection.getCallerClass optimization
988 public void setByte(Object obj, byte b)
989 throws IllegalArgumentException, IllegalAccessException
990 {
991 if (!override) {
992 Class<?> caller = Reflection.getCallerClass();
993 checkAccess(caller, obj);
994 getFieldAccessor().setByte(obj, b);
995 return;
996 }
997
998 FieldAccessor fa = getOverrideFieldAccessor();
999 if (!Modifier.isFinal(modifiers)) {
1000 fa.setByte(obj, b);
1001 } else {
1002 setFinal(Reflection.getCallerClass(), obj, () -> fa.setByte(obj, b));
1003 }
1004 }
1005
1006 /**
1007 * Sets the value of a field as a {@code char} on the specified object.
1008 * This method is equivalent to
1009 * {@code set(obj, cObj)},
1010 * where {@code cObj} is a {@code Character} object and
1011 * {@code cObj.charValue() == c}.
1012 *
1013 * @param obj the object whose field should be modified
1014 * @param c the new value for the field of {@code obj}
1015 * being modified
1016 *
1017 * @throws IllegalAccessException if this {@code Field} object
1018 * is enforcing Java language access control and the underlying
1019 * field is either inaccessible or final;
1020 * or if this {@code Field} object has no write access.
1021 * @throws IllegalArgumentException if the specified object is not an
1022 * instance of the class or interface declaring the underlying
1023 * field (or a subclass or implementor thereof),
1024 * or if an unwrapping conversion fails.
1025 * @throws NullPointerException if the specified object is null
1026 * and the field is an instance field.
1027 * @throws ExceptionInInitializerError if the initialization provoked
1028 * by this method fails.
1029 * @see Field#set
1030 */
1031 @CallerSensitive
1032 @ForceInline // to ensure Reflection.getCallerClass optimization
1033 public void setChar(Object obj, char c)
1034 throws IllegalArgumentException, IllegalAccessException
1035 {
1036 if (!override) {
1037 Class<?> caller = Reflection.getCallerClass();
1038 checkAccess(caller, obj);
1039 getFieldAccessor().setChar(obj, c);
1040 return;
1041 }
1042
1043 FieldAccessor fa = getOverrideFieldAccessor();
1044 if (!Modifier.isFinal(modifiers)) {
1045 fa.setChar(obj, c);
1046 } else {
1047 setFinal(Reflection.getCallerClass(), obj, () -> fa.setChar(obj, c));
1048 }
1049 }
1050
1051 /**
1052 * Sets the value of a field as a {@code short} on the specified object.
1053 * This method is equivalent to
1054 * {@code set(obj, sObj)},
1055 * where {@code sObj} is a {@code Short} object and
1056 * {@code sObj.shortValue() == s}.
1057 *
1058 * @param obj the object whose field should be modified
1059 * @param s the new value for the field of {@code obj}
1060 * being modified
1061 *
1062 * @throws IllegalAccessException if this {@code Field} object
1063 * is enforcing Java language access control and the underlying
1064 * field is either inaccessible or final;
1065 * or if this {@code Field} object has no write access.
1066 * @throws IllegalArgumentException if the specified object is not an
1067 * instance of the class or interface declaring the underlying
1068 * field (or a subclass or implementor thereof),
1069 * or if an unwrapping conversion fails.
1070 * @throws NullPointerException if the specified object is null
1071 * and the field is an instance field.
1072 * @throws ExceptionInInitializerError if the initialization provoked
1073 * by this method fails.
1074 * @see Field#set
1075 */
1076 @CallerSensitive
1077 @ForceInline // to ensure Reflection.getCallerClass optimization
1078 public void setShort(Object obj, short s)
1079 throws IllegalArgumentException, IllegalAccessException
1080 {
1081 if (!override) {
1082 Class<?> caller = Reflection.getCallerClass();
1083 checkAccess(caller, obj);
1084 getFieldAccessor().setShort(obj, s);
1085 return;
1086 }
1087
1088 FieldAccessor fa = getOverrideFieldAccessor();
1089 if (!Modifier.isFinal(modifiers)) {
1090 fa.setShort(obj, s);
1091 } else {
1092 setFinal(Reflection.getCallerClass(), obj, () -> fa.setShort(obj, s));
1093 }
1094 }
1095
1096 /**
1097 * Sets the value of a field as an {@code int} on the specified object.
1098 * This method is equivalent to
1099 * {@code set(obj, iObj)},
1100 * where {@code iObj} is an {@code Integer} object and
1101 * {@code iObj.intValue() == i}.
1102 *
1103 * @param obj the object whose field should be modified
1104 * @param i the new value for the field of {@code obj}
1105 * being modified
1106 *
1107 * @throws IllegalAccessException if this {@code Field} object
1108 * is enforcing Java language access control and the underlying
1109 * field is either inaccessible or final;
1110 * or if this {@code Field} object has no write access.
1111 * @throws IllegalArgumentException if the specified object is not an
1112 * instance of the class or interface declaring the underlying
1113 * field (or a subclass or implementor thereof),
1114 * or if an unwrapping conversion fails.
1115 * @throws NullPointerException if the specified object is null
1116 * and the field is an instance field.
1117 * @throws ExceptionInInitializerError if the initialization provoked
1118 * by this method fails.
1119 * @see Field#set
1120 */
1121 @CallerSensitive
1122 @ForceInline // to ensure Reflection.getCallerClass optimization
1123 public void setInt(Object obj, int i)
1124 throws IllegalArgumentException, IllegalAccessException
1125 {
1126 if (!override) {
1127 Class<?> caller = Reflection.getCallerClass();
1128 checkAccess(caller, obj);
1129 getFieldAccessor().setInt(obj, i);
1130 return;
1131 }
1132
1133 FieldAccessor fa = getOverrideFieldAccessor();
1134 if (!Modifier.isFinal(modifiers)) {
1135 fa.setInt(obj, i);
1136 } else {
1137 setFinal(Reflection.getCallerClass(), obj, () -> fa.setInt(obj, i));
1138 }
1139 }
1140
1141 /**
1142 * Sets the value of a field as a {@code long} on the specified object.
1143 * This method is equivalent to
1144 * {@code set(obj, lObj)},
1145 * where {@code lObj} is a {@code Long} object and
1146 * {@code lObj.longValue() == l}.
1147 *
1148 * @param obj the object whose field should be modified
1149 * @param l the new value for the field of {@code obj}
1150 * being modified
1151 *
1152 * @throws IllegalAccessException if this {@code Field} object
1153 * is enforcing Java language access control and the underlying
1154 * field is either inaccessible or final;
1155 * or if this {@code Field} object has no write access.
1156 * @throws IllegalArgumentException if the specified object is not an
1157 * instance of the class or interface declaring the underlying
1158 * field (or a subclass or implementor thereof),
1159 * or if an unwrapping conversion fails.
1160 * @throws NullPointerException if the specified object is null
1161 * and the field is an instance field.
1162 * @throws ExceptionInInitializerError if the initialization provoked
1163 * by this method fails.
1164 * @see Field#set
1165 */
1166 @CallerSensitive
1167 @ForceInline // to ensure Reflection.getCallerClass optimization
1168 public void setLong(Object obj, long l)
1169 throws IllegalArgumentException, IllegalAccessException
1170 {
1171 if (!override) {
1172 Class<?> caller = Reflection.getCallerClass();
1173 checkAccess(caller, obj);
1174 getFieldAccessor().setLong(obj, l);
1175 return;
1176 }
1177
1178 FieldAccessor fa = getOverrideFieldAccessor();
1179 if (!Modifier.isFinal(modifiers)) {
1180 fa.setLong(obj, l);
1181 } else {
1182 setFinal(Reflection.getCallerClass(), obj, () -> fa.setLong(obj, l));
1183 }
1184 }
1185
1186 /**
1187 * Sets the value of a field as a {@code float} on the specified object.
1188 * This method is equivalent to
1189 * {@code set(obj, fObj)},
1190 * where {@code fObj} is a {@code Float} object and
1191 * {@code fObj.floatValue() == f}.
1192 *
1193 * @param obj the object whose field should be modified
1194 * @param f the new value for the field of {@code obj}
1195 * being modified
1196 *
1197 * @throws IllegalAccessException if this {@code Field} object
1198 * is enforcing Java language access control and the underlying
1199 * field is either inaccessible or final;
1200 * or if this {@code Field} object has no write access.
1201 * @throws IllegalArgumentException if the specified object is not an
1202 * instance of the class or interface declaring the underlying
1203 * field (or a subclass or implementor thereof),
1204 * or if an unwrapping conversion fails.
1205 * @throws NullPointerException if the specified object is null
1206 * and the field is an instance field.
1207 * @throws ExceptionInInitializerError if the initialization provoked
1208 * by this method fails.
1209 * @see Field#set
1210 */
1211 @CallerSensitive
1212 @ForceInline // to ensure Reflection.getCallerClass optimization
1213 public void setFloat(Object obj, float f)
1214 throws IllegalArgumentException, IllegalAccessException
1215 {
1216 if (!override) {
1217 Class<?> caller = Reflection.getCallerClass();
1218 checkAccess(caller, obj);
1219 getFieldAccessor().setFloat(obj, f);
1220 return;
1221 }
1222
1223 FieldAccessor fa = getOverrideFieldAccessor();
1224 if (!Modifier.isFinal(modifiers)) {
1225 fa.setFloat(obj, f);
1226 } else {
1227 setFinal(Reflection.getCallerClass(), obj, () -> fa.setFloat(obj, f));
1228 }
1229 }
1230
1231 /**
1232 * Sets the value of a field as a {@code double} on the specified object.
1233 * This method is equivalent to
1234 * {@code set(obj, dObj)},
1235 * where {@code dObj} is a {@code Double} object and
1236 * {@code dObj.doubleValue() == d}.
1237 *
1238 * @param obj the object whose field should be modified
1239 * @param d the new value for the field of {@code obj}
1240 * being modified
1241 *
1242 * @throws IllegalAccessException if this {@code Field} object
1243 * is enforcing Java language access control and the underlying
1244 * field is either inaccessible or final;
1245 * or if this {@code Field} object has no write access.
1246 * @throws IllegalArgumentException if the specified object is not an
1247 * instance of the class or interface declaring the underlying
1248 * field (or a subclass or implementor thereof),
1249 * or if an unwrapping conversion fails.
1250 * @throws NullPointerException if the specified object is null
1251 * and the field is an instance field.
1252 * @throws ExceptionInInitializerError if the initialization provoked
1253 * by this method fails.
1254 * @see Field#set
1255 */
1256 @CallerSensitive
1257 @ForceInline // to ensure Reflection.getCallerClass optimization
1258 public void setDouble(Object obj, double d)
1259 throws IllegalArgumentException, IllegalAccessException
1260 {
1261 if (!override) {
1262 Class<?> caller = Reflection.getCallerClass();
1263 checkAccess(caller, obj);
1264 getFieldAccessor().setDouble(obj, d);
1265 return;
1266 }
1267
1268 FieldAccessor fa = getOverrideFieldAccessor();
1269 if (!Modifier.isFinal(modifiers)) {
1270 fa.setDouble(obj, d);
1271 } else {
1272 setFinal(Reflection.getCallerClass(), obj, () -> fa.setDouble(obj, d));
1273 }
1274 }
1275
1276 // check access to field
1277 private void checkAccess(Class<?> caller, Object obj)
1278 throws IllegalAccessException
1279 {
1280 checkAccess(caller, clazz,
1281 Modifier.isStatic(modifiers) ? null : obj.getClass(),
1282 modifiers);
1283 }
1284
1285 private FieldAccessor getFieldAccessor() {
1286 FieldAccessor a = fieldAccessor;
1287 return (a != null) ? a : acquireFieldAccessor();
1288 }
1289
1290 private FieldAccessor getOverrideFieldAccessor() {
1291 FieldAccessor a = overrideFieldAccessor;
1292 return (a != null) ? a : acquireOverrideFieldAccessor();
1293 }
1294
1295 // NOTE that there is no synchronization used here. It is correct
1296 // (though not efficient) to generate more than one FieldAccessor
1297 // for a given Field. However, avoiding synchronization will
1298 // probably make the implementation more scalable.
1299 private FieldAccessor acquireFieldAccessor() {
1300 // First check to see if one has been created yet, and take it
1301 // if so
1302 Field root = this.root;
1303 FieldAccessor tmp = root == null ? null : root.fieldAccessor;
1304 if (tmp != null) {
1305 fieldAccessor = tmp;
1306 } else {
1307 // Otherwise fabricate one and propagate it up to the root
1308 tmp = reflectionFactory.newFieldAccessor(this, false);
1309 setFieldAccessor(tmp);
1310 }
1311 return tmp;
1312 }
1313
1314 private FieldAccessor acquireOverrideFieldAccessor() {
1315 // First check to see if one has been created yet, and take it
1316 // if so
1317 Field root = this.root;
1318 FieldAccessor tmp = root == null ? null : root.overrideFieldAccessor;
1319 if (tmp != null) {
1320 overrideFieldAccessor = tmp;
1321 } else {
1322 // Otherwise fabricate one and propagate it up to the root
1323 tmp = reflectionFactory.newFieldAccessor(this, true);
1324 setOverrideFieldAccessor(tmp);
1325 }
1326 return tmp;
1327 }
1328
1329 // Sets the fieldAccessor for this Field object and
1330 // (recursively) its root
1331 private void setFieldAccessor(FieldAccessor accessor) {
1332 fieldAccessor = accessor;
1333 // Propagate up
1334 Field root = this.root;
1335 if (root != null) {
1336 root.setFieldAccessor(accessor);
1337 }
1338 }
1339
1340 // Sets the overrideFieldAccessor for this Field object and
1341 // (recursively) its root
1342 private void setOverrideFieldAccessor(FieldAccessor accessor) {
1343 overrideFieldAccessor = accessor;
1344 // Propagate up
1345 Field root = this.root;
1346 if (root != null) {
1347 root.setOverrideFieldAccessor(accessor);
1348 }
1349 }
1350
1351 @Override
1352 /* package-private */ Field getRoot() {
1353 return root;
1354 }
1355
1356 private static final int TRUST_FINAL = 0x0010;
1357 private static final int NULL_RESTRICTED = 0x0020;
1358
1359 /* package-private */ boolean isTrustedFinal() {
1360 return (flags & TRUST_FINAL) == TRUST_FINAL;
1361 }
1362
1363 /* package-private */ boolean isNullRestricted() {
1364 return (flags & NULL_RESTRICTED) == NULL_RESTRICTED;
1365 }
1366
1367 /**
1368 * {@inheritDoc}
1369 *
1370 * @throws NullPointerException {@inheritDoc}
1371 * @since 1.5
1372 */
1373 @Override
1374 public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
1375 Objects.requireNonNull(annotationClass);
1376 return annotationClass.cast(declaredAnnotations().get(annotationClass));
1377 }
1378
1379 /**
1380 * {@inheritDoc}
1381 *
1382 * @throws NullPointerException {@inheritDoc}
1383 * @since 1.8
1384 */
1385 @Override
1386 public <T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass) {
1387 Objects.requireNonNull(annotationClass);
1388
1389 return AnnotationSupport.getDirectlyAndIndirectlyPresent(declaredAnnotations(), annotationClass);
1390 }
1391
1392 /**
1393 * {@inheritDoc}
1394 */
1395 @Override
1396 public Annotation[] getDeclaredAnnotations() {
1397 return AnnotationParser.toArray(declaredAnnotations());
1398 }
1399
1400 private transient volatile Map<Class<? extends Annotation>, Annotation> declaredAnnotations;
1401
1402 private Map<Class<? extends Annotation>, Annotation> declaredAnnotations() {
1403 Map<Class<? extends Annotation>, Annotation> declAnnos;
1404 if ((declAnnos = declaredAnnotations) == null) {
1405 synchronized (this) {
1406 if ((declAnnos = declaredAnnotations) == null) {
1407 Field root = this.root;
1408 if (root != null) {
1409 declAnnos = root.declaredAnnotations();
1410 } else {
1411 declAnnos = AnnotationParser.parseAnnotations(
1412 annotations,
1413 SharedSecrets.getJavaLangAccess()
1414 .getConstantPool(getDeclaringClass()),
1415 getDeclaringClass());
1416 }
1417 declaredAnnotations = declAnnos;
1418 }
1419 }
1420 }
1421 return declAnnos;
1422 }
1423
1424 private native byte[] getTypeAnnotationBytes0();
1425
1426 /**
1427 * Returns an AnnotatedType object that represents the use of a type to specify
1428 * the declared type of the field represented by this Field.
1429 * @return an object representing the declared type of the field
1430 * represented by this Field
1431 *
1432 * @since 1.8
1433 */
1434 public AnnotatedType getAnnotatedType() {
1435 return TypeAnnotationParser.buildAnnotatedType(getTypeAnnotationBytes0(),
1436 SharedSecrets.getJavaLangAccess().
1437 getConstantPool(getDeclaringClass()),
1438 this,
1439 getDeclaringClass(),
1440 getGenericType(),
1441 TypeAnnotation.TypeAnnotationTarget.FIELD);
1442 }
1443
1444 /**
1445 * A function that sets a field to a value.
1446 */
1447 @FunctionalInterface
1448 private interface FieldSetter {
1449 void setFieldValue() throws IllegalAccessException;
1450 }
1451
1452 /**
1453 * Attempts to set a final field.
1454 */
1455 private void setFinal(Class<?> caller, Object obj, FieldSetter setter) throws IllegalAccessException {
1456 if (obj != null && isFinalInstanceInNormalClass()) {
1457 preSetFinal(caller, false);
1458 setter.setFieldValue();
1459 postSetFinal(caller, false);
1460 } else {
1461 // throws IllegalAccessException if static, or field in record or hidden class
1462 setter.setFieldValue();
1463 }
1464 }
1465
1466 /**
1467 * Return true if this field is a final instance field in a normal class (not a
1468 * record class or hidden class),
1469 */
1470 private boolean isFinalInstanceInNormalClass() {
1471 return Modifier.isFinal(modifiers)
1472 && !Modifier.isStatic(modifiers)
1473 && !clazz.isRecord()
1474 && !clazz.isHidden();
1475 }
1476
1477 /**
1478 * Check that the caller is allowed to unreflect for mutation a final instance field
1479 * in a normal class.
1480 * @throws IllegalAccessException if not allowed
1481 */
1482 void checkAllowedToUnreflectFinalSetter(Class<?> caller) throws IllegalAccessException {
1483 Objects.requireNonNull(caller);
1484 preSetFinal(caller, true);
1485 postSetFinal(caller, true);
1486 }
1487
1488 /**
1489 * Invoke before attempting to mutate, or unreflect for mutation, a final instance
1490 * field in a normal class.
1491 * @throws IllegalAccessException if not allowed
1492 */
1493 private void preSetFinal(Class<?> caller, boolean unreflect) throws IllegalAccessException {
1494 assert isFinalInstanceInNormalClass();
1495
1496 if (caller != null) {
1497 // check if declaring class in package that is open to caller, or public field
1498 // and declaring class is public in package exported to caller
1499 if (!isFinalDeeplyAccessible(caller)) {
1500 throw new IllegalAccessException(notAccessibleToCallerMessage(caller, unreflect));
1501 }
1502 } else {
1503 // no java caller, only allowed if field is public in exported package
1504 if (!Reflection.verifyPublicMemberAccess(clazz, modifiers)) {
1505 throw new IllegalAccessException(notAccessibleToNoCallerMessage(unreflect));
1506 }
1507 }
1508
1509 // check if field mutation is enabled for caller module or illegal final field
1510 // mutation is allowed
1511 var mode = ModuleBootstrap.illegalFinalFieldMutation();
1512 if (mode == ModuleBootstrap.IllegalFinalFieldMutation.DENY
1513 && !Modules.isFinalMutationEnabled(moduleToCheck(caller))) {
1514 throw new IllegalAccessException(callerNotAllowedToMutateMessage(caller, unreflect));
1515 }
1516 }
1517
1518 /**
1519 * Invoke after mutating a final instance field, or when unreflecting a final instance
1520 * field for mutation, to print a warning and record a JFR event.
1521 */
1522 private void postSetFinal(Class<?> caller, boolean unreflect) {
1523 assert isFinalInstanceInNormalClass();
1524
1525 var mode = ModuleBootstrap.illegalFinalFieldMutation();
1526 if (mode == ModuleBootstrap.IllegalFinalFieldMutation.WARN) {
1527 // first mutation prints warning
1528 Module moduleToCheck = moduleToCheck(caller);
1529 if (Modules.tryEnableFinalMutation(moduleToCheck)) {
1530 String warningMsg = finalFieldMutationWarning(caller, unreflect);
1531 String targetModule = (caller != null && moduleToCheck.isNamed())
1532 ? moduleToCheck.getName()
1533 : "ALL-UNNAMED";
1534 VM.initialErr().printf("""
1535 WARNING: %s
1536 WARNING: Use --enable-final-field-mutation=%s to avoid a warning
1537 WARNING: Mutating final fields will be blocked in a future release unless final field mutation is enabled
1538 """, warningMsg, targetModule);
1539 }
1540 } else if (mode == ModuleBootstrap.IllegalFinalFieldMutation.DEBUG) {
1541 // print warning and stack trace
1542 var sb = new StringBuilder(finalFieldMutationWarning(caller, unreflect));
1543 StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE)
1544 .forEach(sf -> {
1545 sb.append(System.lineSeparator()).append("\tat " + sf);
1546 });
1547 VM.initialErr().println(sb);
1548 }
1549
1550 // record JFR event
1551 FinalFieldMutationEvent.offer(getDeclaringClass(), getName());
1552 }
1553
1554 /**
1555 * Returns true if this final field is "deeply accessible" to the caller.
1556 * The field is deeply accessible if declaring class is in a package that is open
1557 * to the caller's module, or the field is public in a public class that is exported
1558 * to the caller's module.
1559 *
1560 * Updates to the module of the declaring class at runtime with {@code Module.addExports}
1561 * or {@code Module.addOpens} have no impact on the result of this method.
1562 */
1563 private boolean isFinalDeeplyAccessible(Class<?> caller) {
1564 assert isFinalInstanceInNormalClass();
1565
1566 // all fields in unnamed modules are deeply accessible
1567 Module declaringModule = clazz.getModule();
1568 if (!declaringModule.isNamed()) return true;
1569
1570 // all fields in the caller's module are deeply accessible
1571 Module callerModule = caller.getModule();
1572 if (callerModule == declaringModule) return true;
1573
1574 // public field, public class, package exported to caller's module
1575 String pn = clazz.getPackageName();
1576 if (Modifier.isPublic(modifiers)
1577 && Modifier.isPublic(clazz.getModifiers())
1578 && Modules.isStaticallyExported(declaringModule, pn, callerModule)) {
1579 return true;
1580 }
1581
1582 // package open to caller's module
1583 return Modules.isStaticallyOpened(declaringModule, pn, callerModule);
1584 }
1585
1586 /**
1587 * Returns the Module to use for access checks with the given caller.
1588 */
1589 private Module moduleToCheck(Class<?> caller) {
1590 if (caller != null) {
1591 return caller.getModule();
1592 } else {
1593 // no java caller, only allowed if field is public in exported package
1594 return ClassLoaders.appClassLoader().getUnnamedModule();
1595 }
1596 }
1597
1598 /**
1599 * Returns the warning message to print when this final field is mutated by
1600 * the given possibly-null caller.
1601 */
1602 private String finalFieldMutationWarning(Class<?> caller, boolean unreflect) {
1603 assert Modifier.isFinal(modifiers);
1604 String source;
1605 if (caller != null) {
1606 source = caller + " in " + caller.getModule();
1607 CodeSource cs = caller.getProtectionDomain().getCodeSource();
1608 if (cs != null) {
1609 URL url = cs.getLocation();
1610 if (url != null) {
1611 source += " (" + url + ")";
1612 }
1613 }
1614 } else {
1615 source = "JNI attached thread with no caller frame";
1616 }
1617 return String.format("Final field %s in %s has been %s by %s",
1618 name,
1619 clazz,
1620 (unreflect) ? "unreflected for mutation" : "mutated reflectively",
1621 source);
1622 }
1623
1624 /**
1625 * Returns the message for an IllegalAccessException when a final field cannot be
1626 * mutated because the declaring class is in a package that is not "deeply accessible"
1627 * to the caller.
1628 */
1629 private String notAccessibleToCallerMessage(Class<?> caller, boolean unreflect) {
1630 String exportsOrOpens = Modifier.isPublic(modifiers)
1631 && Modifier.isPublic(clazz.getModifiers()) ? "exports" : "opens";
1632 return String.format("%s, %s does not explicitly \"%s\" package %s to %s",
1633 cannotSetFieldMessage(caller, unreflect),
1634 clazz.getModule(),
1635 exportsOrOpens,
1636 clazz.getPackageName(),
1637 caller.getModule());
1638 }
1639
1640 /**
1641 * Returns the exception message for the IllegalAccessException when this
1642 * final field cannot be mutated because the caller module is not allowed
1643 * to mutate final fields.
1644 */
1645 private String callerNotAllowedToMutateMessage(Class<?> caller, boolean unreflect) {
1646 if (caller != null) {
1647 return String.format("%s, %s is not allowed to mutate final fields",
1648 cannotSetFieldMessage(caller, unreflect),
1649 caller.getModule());
1650 } else {
1651 return notAccessibleToNoCallerMessage(unreflect);
1652 }
1653 }
1654
1655 /**
1656 * Returns the message for an IllegalAccessException when a field is not
1657 * accessible to a JNI attached thread.
1658 */
1659 private String notAccessibleToNoCallerMessage(boolean unreflect) {
1660 return cannotSetFieldMessage("JNI attached thread with no caller frame cannot", unreflect);
1661 }
1662
1663 /**
1664 * Returns a message to indicate that the caller cannot set/unreflect this final field.
1665 */
1666 private String cannotSetFieldMessage(Class<?> caller, boolean unreflect) {
1667 return cannotSetFieldMessage(caller + " (in " + caller.getModule() + ") cannot", unreflect);
1668 }
1669
1670 /**
1671 * Returns a message to indicate that a field cannot be set/unreflected.
1672 */
1673 private String cannotSetFieldMessage(String prefix, boolean unreflect) {
1674 if (unreflect) {
1675 return prefix + " unreflect final field " + clazz.getName() + "." + name
1676 + " (in " + clazz.getModule() + ") for mutation";
1677 } else {
1678 return prefix + " set final field " + clazz.getName() + "." + name
1679 + " (in " + clazz.getModule() + ")";
1680 }
1681 }
1682 }