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