1 /* 2 * Copyright (c) 1994, 2014, 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; 27 28 import java.lang.reflect.AnnotatedElement; 29 import java.lang.reflect.Array; 30 import java.lang.reflect.GenericArrayType; 31 import java.lang.reflect.GenericDeclaration; 32 import java.lang.reflect.Member; 33 import java.lang.reflect.Field; 34 import java.lang.reflect.Executable; 35 import java.lang.reflect.Method; 36 import java.lang.reflect.Constructor; 37 import java.lang.reflect.Modifier; 38 import java.lang.reflect.Type; 39 import java.lang.reflect.TypeVariable; 40 import java.lang.reflect.InvocationTargetException; 41 import java.lang.reflect.AnnotatedType; 42 import java.lang.ref.SoftReference; 43 import java.io.InputStream; 44 import java.io.ObjectStreamField; 45 import java.security.AccessController; 46 import java.security.PrivilegedAction; 47 import java.util.ArrayList; 48 import java.util.Arrays; 49 import java.util.Collection; 50 import java.util.HashSet; 51 import java.util.LinkedHashMap; 52 import java.util.List; 53 import java.util.Set; 54 import java.util.Map; 55 import java.util.HashMap; 56 import java.util.Objects; 57 import java.util.StringJoiner; 58 import sun.misc.Unsafe; 59 import jdk.internal.HotSpotIntrinsicCandidate; 60 import sun.reflect.CallerSensitive; 61 import sun.reflect.ConstantPool; 62 import sun.reflect.Reflection; 63 import sun.reflect.ReflectionFactory; 64 import sun.reflect.generics.factory.CoreReflectionFactory; 65 import sun.reflect.generics.factory.GenericsFactory; 66 import sun.reflect.generics.repository.ClassRepository; 67 import sun.reflect.generics.repository.MethodRepository; 68 import sun.reflect.generics.repository.ConstructorRepository; 69 import sun.reflect.generics.scope.ClassScope; 70 import sun.security.util.SecurityConstants; 71 import java.lang.annotation.Annotation; 72 import java.lang.reflect.Proxy; 73 import sun.reflect.annotation.*; 74 import sun.reflect.misc.ReflectUtil; 75 76 /** 77 * Instances of the class {@code Class} represent classes and 78 * interfaces in a running Java application. An enum is a kind of 79 * class and an annotation is a kind of interface. Every array also 80 * belongs to a class that is reflected as a {@code Class} object 81 * that is shared by all arrays with the same element type and number 82 * of dimensions. The primitive Java types ({@code boolean}, 83 * {@code byte}, {@code char}, {@code short}, 84 * {@code int}, {@code long}, {@code float}, and 85 * {@code double}), and the keyword {@code void} are also 86 * represented as {@code Class} objects. 87 * 88 * <p> {@code Class} has no public constructor. Instead {@code Class} 89 * objects are constructed automatically by the Java Virtual Machine as classes 90 * are loaded and by calls to the {@code defineClass} method in the class 91 * loader. 92 * 93 * <p> The following example uses a {@code Class} object to print the 94 * class name of an object: 95 * 96 * <blockquote><pre> 97 * void printClassName(Object obj) { 98 * System.out.println("The class of " + obj + 99 * " is " + obj.getClass().getName()); 100 * } 101 * </pre></blockquote> 102 * 103 * <p> It is also possible to get the {@code Class} object for a named 104 * type (or for void) using a class literal. See Section 15.8.2 of 105 * <cite>The Java™ Language Specification</cite>. 106 * For example: 107 * 108 * <blockquote> 109 * {@code System.out.println("The name of class Foo is: "+Foo.class.getName());} 110 * </blockquote> 111 * 112 * @param <T> the type of the class modeled by this {@code Class} 113 * object. For example, the type of {@code String.class} is {@code 114 * Class<String>}. Use {@code Class<?>} if the class being modeled is 115 * unknown. 116 * 117 * @author unascribed 118 * @see java.lang.ClassLoader#defineClass(byte[], int, int) 119 * @since 1.0 120 */ 121 public final class Class<T> implements java.io.Serializable, 122 GenericDeclaration, 123 Type, 124 AnnotatedElement { 125 private static final int ANNOTATION= 0x00002000; 126 private static final int ENUM = 0x00004000; 127 private static final int SYNTHETIC = 0x00001000; 128 129 private static native void registerNatives(); 130 static { 131 registerNatives(); 132 } 133 134 /* 135 * Private constructor. Only the Java Virtual Machine creates Class objects. 136 * This constructor is not used and prevents the default constructor being 137 * generated. 138 */ 139 private Class(ClassLoader loader, Class<?> arrayComponentType) { 140 // Initialize final field for classLoader. The initialization value of non-null 141 // prevents future JIT optimizations from assuming this final field is null. 142 classLoader = loader; 143 componentType = arrayComponentType; 144 } 145 146 /** 147 * Converts the object to a string. The string representation is the 148 * string "class" or "interface", followed by a space, and then by the 149 * fully qualified name of the class in the format returned by 150 * {@code getName}. If this {@code Class} object represents a 151 * primitive type, this method returns the name of the primitive type. If 152 * this {@code Class} object represents void this method returns 153 * "void". If this {@code Class} object represents an array type, 154 * this method returns "class " followed by {@code getName}. 155 * 156 * @return a string representation of this class object. 157 */ 158 public String toString() { 159 return (isInterface() ? "interface " : (isPrimitive() ? "" : "class ")) 160 + getName(); 161 } 162 163 /** 164 * Returns a string describing this {@code Class}, including 165 * information about modifiers and type parameters. 166 * 167 * The string is formatted as a list of type modifiers, if any, 168 * followed by the kind of type (empty string for primitive types 169 * and {@code class}, {@code enum}, {@code interface}, or 170 * <code>@</code>{@code interface}, as appropriate), followed 171 * by the type's name, followed by an angle-bracketed 172 * comma-separated list of the type's type parameters, if any. 173 * 174 * A space is used to separate modifiers from one another and to 175 * separate any modifiers from the kind of type. The modifiers 176 * occur in canonical order. If there are no type parameters, the 177 * type parameter list is elided. 178 * 179 * For an array type, the string starts with the type name, 180 * followed by an angle-bracketed comma-separated list of the 181 * type's type parameters, if any, followed by a sequence of 182 * {@code []} characters, one set of brackets per dimension of 183 * the array. 184 * 185 * <p>Note that since information about the runtime representation 186 * of a type is being generated, modifiers not present on the 187 * originating source code or illegal on the originating source 188 * code may be present. 189 * 190 * @return a string describing this {@code Class}, including 191 * information about modifiers and type parameters 192 * 193 * @since 1.8 194 */ 195 public String toGenericString() { 196 if (isPrimitive()) { 197 return toString(); 198 } else { 199 StringBuilder sb = new StringBuilder(); 200 Class<?> component = this; 201 int arrayDepth = 0; 202 203 if (isArray()) { 204 do { 205 arrayDepth++; 206 component = component.getComponentType(); 207 } while (component.isArray()); 208 sb.append(component.getName()); 209 } else { 210 // Class modifiers are a superset of interface modifiers 211 int modifiers = getModifiers() & Modifier.classModifiers(); 212 if (modifiers != 0) { 213 sb.append(Modifier.toString(modifiers)); 214 sb.append(' '); 215 } 216 217 if (isAnnotation()) { 218 sb.append('@'); 219 } 220 if (isInterface()) { // Note: all annotation types are interfaces 221 sb.append("interface"); 222 } else { 223 if (isEnum()) 224 sb.append("enum"); 225 else 226 sb.append("class"); 227 } 228 sb.append(' '); 229 sb.append(getName()); 230 } 231 232 TypeVariable<?>[] typeparms = component.getTypeParameters(); 233 if (typeparms.length > 0) { 234 boolean first = true; 235 sb.append('<'); 236 for(TypeVariable<?> typeparm: typeparms) { 237 if (!first) 238 sb.append(','); 239 sb.append(typeparm.getTypeName()); 240 first = false; 241 } 242 sb.append('>'); 243 } 244 245 for (int i = 0; i < arrayDepth; i++) 246 sb.append("[]"); 247 248 return sb.toString(); 249 } 250 } 251 252 /** 253 * Returns the {@code Class} object associated with the class or 254 * interface with the given string name. Invoking this method is 255 * equivalent to: 256 * 257 * <blockquote> 258 * {@code Class.forName(className, true, currentLoader)} 259 * </blockquote> 260 * 261 * where {@code currentLoader} denotes the defining class loader of 262 * the current class. 263 * 264 * <p> For example, the following code fragment returns the 265 * runtime {@code Class} descriptor for the class named 266 * {@code java.lang.Thread}: 267 * 268 * <blockquote> 269 * {@code Class t = Class.forName("java.lang.Thread")} 270 * </blockquote> 271 * <p> 272 * A call to {@code forName("X")} causes the class named 273 * {@code X} to be initialized. 274 * 275 * @param className the fully qualified name of the desired class. 276 * @return the {@code Class} object for the class with the 277 * specified name. 278 * @exception LinkageError if the linkage fails 279 * @exception ExceptionInInitializerError if the initialization provoked 280 * by this method fails 281 * @exception ClassNotFoundException if the class cannot be located 282 */ 283 @CallerSensitive 284 public static Class<?> forName(String className) 285 throws ClassNotFoundException { 286 Class<?> caller = Reflection.getCallerClass(); 287 return forName0(className, true, ClassLoader.getClassLoader(caller), caller); 288 } 289 290 291 /** 292 * Returns the {@code Class} object associated with the class or 293 * interface with the given string name, using the given class loader. 294 * Given the fully qualified name for a class or interface (in the same 295 * format returned by {@code getName}) this method attempts to 296 * locate, load, and link the class or interface. The specified class 297 * loader is used to load the class or interface. If the parameter 298 * {@code loader} is null, the class is loaded through the bootstrap 299 * class loader. The class is initialized only if the 300 * {@code initialize} parameter is {@code true} and if it has 301 * not been initialized earlier. 302 * 303 * <p> If {@code name} denotes a primitive type or void, an attempt 304 * will be made to locate a user-defined class in the unnamed package whose 305 * name is {@code name}. Therefore, this method cannot be used to 306 * obtain any of the {@code Class} objects representing primitive 307 * types or void. 308 * 309 * <p> If {@code name} denotes an array class, the component type of 310 * the array class is loaded but not initialized. 311 * 312 * <p> For example, in an instance method the expression: 313 * 314 * <blockquote> 315 * {@code Class.forName("Foo")} 316 * </blockquote> 317 * 318 * is equivalent to: 319 * 320 * <blockquote> 321 * {@code Class.forName("Foo", true, this.getClass().getClassLoader())} 322 * </blockquote> 323 * 324 * Note that this method throws errors related to loading, linking or 325 * initializing as specified in Sections 12.2, 12.3 and 12.4 of <em>The 326 * Java Language Specification</em>. 327 * Note that this method does not check whether the requested class 328 * is accessible to its caller. 329 * 330 * <p> If the {@code loader} is {@code null}, and a security 331 * manager is present, and the caller's class loader is not null, then this 332 * method calls the security manager's {@code checkPermission} method 333 * with a {@code RuntimePermission("getClassLoader")} permission to 334 * ensure it's ok to access the bootstrap class loader. 335 * 336 * @param name fully qualified name of the desired class 337 * @param initialize if {@code true} the class will be initialized. 338 * See Section 12.4 of <em>The Java Language Specification</em>. 339 * @param loader class loader from which the class must be loaded 340 * @return class object representing the desired class 341 * 342 * @exception LinkageError if the linkage fails 343 * @exception ExceptionInInitializerError if the initialization provoked 344 * by this method fails 345 * @exception ClassNotFoundException if the class cannot be located by 346 * the specified class loader 347 * 348 * @see java.lang.Class#forName(String) 349 * @see java.lang.ClassLoader 350 * @since 1.2 351 */ 352 @CallerSensitive 353 public static Class<?> forName(String name, boolean initialize, 354 ClassLoader loader) 355 throws ClassNotFoundException 356 { 357 Class<?> caller = null; 358 SecurityManager sm = System.getSecurityManager(); 359 if (sm != null) { 360 // Reflective call to get caller class is only needed if a security manager 361 // is present. Avoid the overhead of making this call otherwise. 362 caller = Reflection.getCallerClass(); 363 if (sun.misc.VM.isSystemDomainLoader(loader)) { 364 ClassLoader ccl = ClassLoader.getClassLoader(caller); 365 if (!sun.misc.VM.isSystemDomainLoader(ccl)) { 366 sm.checkPermission( 367 SecurityConstants.GET_CLASSLOADER_PERMISSION); 368 } 369 } 370 } 371 return forName0(name, initialize, loader, caller); 372 } 373 374 /** Called after security check for system loader access checks have been made. */ 375 private static native Class<?> forName0(String name, boolean initialize, 376 ClassLoader loader, 377 Class<?> caller) 378 throws ClassNotFoundException; 379 380 /** 381 * Creates a new instance of the class represented by this {@code Class} 382 * object. The class is instantiated as if by a {@code new} 383 * expression with an empty argument list. The class is initialized if it 384 * has not already been initialized. 385 * 386 * <p>Note that this method propagates any exception thrown by the 387 * nullary constructor, including a checked exception. Use of 388 * this method effectively bypasses the compile-time exception 389 * checking that would otherwise be performed by the compiler. 390 * The {@link 391 * java.lang.reflect.Constructor#newInstance(java.lang.Object...) 392 * Constructor.newInstance} method avoids this problem by wrapping 393 * any exception thrown by the constructor in a (checked) {@link 394 * java.lang.reflect.InvocationTargetException}. 395 * 396 * @return a newly allocated instance of the class represented by this 397 * object. 398 * @throws IllegalAccessException if the class or its nullary 399 * constructor is not accessible. 400 * @throws InstantiationException 401 * if this {@code Class} represents an abstract class, 402 * an interface, an array class, a primitive type, or void; 403 * or if the class has no nullary constructor; 404 * or if the instantiation fails for some other reason. 405 * @throws ExceptionInInitializerError if the initialization 406 * provoked by this method fails. 407 * @throws SecurityException 408 * If a security manager, <i>s</i>, is present and 409 * the caller's class loader is not the same as or an 410 * ancestor of the class loader for the current class and 411 * invocation of {@link SecurityManager#checkPackageAccess 412 * s.checkPackageAccess()} denies access to the package 413 * of this class. 414 */ 415 @CallerSensitive 416 public T newInstance() 417 throws InstantiationException, IllegalAccessException 418 { 419 if (System.getSecurityManager() != null) { 420 checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), false); 421 } 422 423 // NOTE: the following code may not be strictly correct under 424 // the current Java memory model. 425 426 // Constructor lookup 427 if (cachedConstructor == null) { 428 if (this == Class.class) { 429 throw new IllegalAccessException( 430 "Can not call newInstance() on the Class for java.lang.Class" 431 ); 432 } 433 try { 434 Class<?>[] empty = {}; 435 final Constructor<T> c = getConstructor0(empty, Member.DECLARED); 436 // Disable accessibility checks on the constructor 437 // since we have to do the security check here anyway 438 // (the stack depth is wrong for the Constructor's 439 // security check to work) 440 java.security.AccessController.doPrivileged( 441 new java.security.PrivilegedAction<>() { 442 public Void run() { 443 c.setAccessible(true); 444 return null; 445 } 446 }); 447 cachedConstructor = c; 448 } catch (NoSuchMethodException e) { 449 throw (InstantiationException) 450 new InstantiationException(getName()).initCause(e); 451 } 452 } 453 Constructor<T> tmpConstructor = cachedConstructor; 454 // Security check (same as in java.lang.reflect.Constructor) 455 int modifiers = tmpConstructor.getModifiers(); 456 if (!Reflection.quickCheckMemberAccess(this, modifiers)) { 457 Class<?> caller = Reflection.getCallerClass(); 458 if (newInstanceCallerCache != caller) { 459 Reflection.ensureMemberAccess(caller, this, null, modifiers); 460 newInstanceCallerCache = caller; 461 } 462 } 463 // Run constructor 464 try { 465 return tmpConstructor.newInstance((Object[])null); 466 } catch (InvocationTargetException e) { 467 Unsafe.getUnsafe().throwException(e.getTargetException()); 468 // Not reached 469 return null; 470 } 471 } 472 private volatile transient Constructor<T> cachedConstructor; 473 private volatile transient Class<?> newInstanceCallerCache; 474 475 476 /** 477 * Determines if the specified {@code Object} is assignment-compatible 478 * with the object represented by this {@code Class}. This method is 479 * the dynamic equivalent of the Java language {@code instanceof} 480 * operator. The method returns {@code true} if the specified 481 * {@code Object} argument is non-null and can be cast to the 482 * reference type represented by this {@code Class} object without 483 * raising a {@code ClassCastException.} It returns {@code false} 484 * otherwise. 485 * 486 * <p> Specifically, if this {@code Class} object represents a 487 * declared class, this method returns {@code true} if the specified 488 * {@code Object} argument is an instance of the represented class (or 489 * of any of its subclasses); it returns {@code false} otherwise. If 490 * this {@code Class} object represents an array class, this method 491 * returns {@code true} if the specified {@code Object} argument 492 * can be converted to an object of the array class by an identity 493 * conversion or by a widening reference conversion; it returns 494 * {@code false} otherwise. If this {@code Class} object 495 * represents an interface, this method returns {@code true} if the 496 * class or any superclass of the specified {@code Object} argument 497 * implements this interface; it returns {@code false} otherwise. If 498 * this {@code Class} object represents a primitive type, this method 499 * returns {@code false}. 500 * 501 * @param obj the object to check 502 * @return true if {@code obj} is an instance of this class 503 * 504 * @since 1.1 505 */ 506 @HotSpotIntrinsicCandidate 507 public native boolean isInstance(Object obj); 508 509 510 /** 511 * Determines if the class or interface represented by this 512 * {@code Class} object is either the same as, or is a superclass or 513 * superinterface of, the class or interface represented by the specified 514 * {@code Class} parameter. It returns {@code true} if so; 515 * otherwise it returns {@code false}. If this {@code Class} 516 * object represents a primitive type, this method returns 517 * {@code true} if the specified {@code Class} parameter is 518 * exactly this {@code Class} object; otherwise it returns 519 * {@code false}. 520 * 521 * <p> Specifically, this method tests whether the type represented by the 522 * specified {@code Class} parameter can be converted to the type 523 * represented by this {@code Class} object via an identity conversion 524 * or via a widening reference conversion. See <em>The Java Language 525 * Specification</em>, sections 5.1.1 and 5.1.4 , for details. 526 * 527 * @param cls the {@code Class} object to be checked 528 * @return the {@code boolean} value indicating whether objects of the 529 * type {@code cls} can be assigned to objects of this class 530 * @exception NullPointerException if the specified Class parameter is 531 * null. 532 * @since 1.1 533 */ 534 @HotSpotIntrinsicCandidate 535 public native boolean isAssignableFrom(Class<?> cls); 536 537 538 /** 539 * Determines if the specified {@code Class} object represents an 540 * interface type. 541 * 542 * @return {@code true} if this object represents an interface; 543 * {@code false} otherwise. 544 */ 545 @HotSpotIntrinsicCandidate 546 public native boolean isInterface(); 547 548 549 /** 550 * Determines if this {@code Class} object represents an array class. 551 * 552 * @return {@code true} if this object represents an array class; 553 * {@code false} otherwise. 554 * @since 1.1 555 */ 556 @HotSpotIntrinsicCandidate 557 public native boolean isArray(); 558 559 560 /** 561 * Determines if the specified {@code Class} object represents a 562 * primitive type. 563 * 564 * <p> There are nine predefined {@code Class} objects to represent 565 * the eight primitive types and void. These are created by the Java 566 * Virtual Machine, and have the same names as the primitive types that 567 * they represent, namely {@code boolean}, {@code byte}, 568 * {@code char}, {@code short}, {@code int}, 569 * {@code long}, {@code float}, and {@code double}. 570 * 571 * <p> These objects may only be accessed via the following public static 572 * final variables, and are the only {@code Class} objects for which 573 * this method returns {@code true}. 574 * 575 * @return true if and only if this class represents a primitive type 576 * 577 * @see java.lang.Boolean#TYPE 578 * @see java.lang.Character#TYPE 579 * @see java.lang.Byte#TYPE 580 * @see java.lang.Short#TYPE 581 * @see java.lang.Integer#TYPE 582 * @see java.lang.Long#TYPE 583 * @see java.lang.Float#TYPE 584 * @see java.lang.Double#TYPE 585 * @see java.lang.Void#TYPE 586 * @since 1.1 587 */ 588 @HotSpotIntrinsicCandidate 589 public native boolean isPrimitive(); 590 591 /** 592 * Returns true if this {@code Class} object represents an annotation 593 * type. Note that if this method returns true, {@link #isInterface()} 594 * would also return true, as all annotation types are also interfaces. 595 * 596 * @return {@code true} if this class object represents an annotation 597 * type; {@code false} otherwise 598 * @since 1.5 599 */ 600 public boolean isAnnotation() { 601 return (getModifiers() & ANNOTATION) != 0; 602 } 603 604 /** 605 * Returns {@code true} if this class is a synthetic class; 606 * returns {@code false} otherwise. 607 * @return {@code true} if and only if this class is a synthetic class as 608 * defined by the Java Language Specification. 609 * @jls 13.1 The Form of a Binary 610 * @since 1.5 611 */ 612 public boolean isSynthetic() { 613 return (getModifiers() & SYNTHETIC) != 0; 614 } 615 616 /** 617 * Returns the name of the entity (class, interface, array class, 618 * primitive type, or void) represented by this {@code Class} object, 619 * as a {@code String}. 620 * 621 * <p> If this class object represents a reference type that is not an 622 * array type then the binary name of the class is returned, as specified 623 * by 624 * <cite>The Java™ Language Specification</cite>. 625 * 626 * <p> If this class object represents a primitive type or void, then the 627 * name returned is a {@code String} equal to the Java language 628 * keyword corresponding to the primitive type or void. 629 * 630 * <p> If this class object represents a class of arrays, then the internal 631 * form of the name consists of the name of the element type preceded by 632 * one or more '{@code [}' characters representing the depth of the array 633 * nesting. The encoding of element type names is as follows: 634 * 635 * <blockquote><table summary="Element types and encodings"> 636 * <tr><th> Element Type <th> <th> Encoding 637 * <tr><td> boolean <td> <td align=center> Z 638 * <tr><td> byte <td> <td align=center> B 639 * <tr><td> char <td> <td align=center> C 640 * <tr><td> class or interface 641 * <td> <td align=center> L<i>classname</i>; 642 * <tr><td> double <td> <td align=center> D 643 * <tr><td> float <td> <td align=center> F 644 * <tr><td> int <td> <td align=center> I 645 * <tr><td> long <td> <td align=center> J 646 * <tr><td> short <td> <td align=center> S 647 * </table></blockquote> 648 * 649 * <p> The class or interface name <i>classname</i> is the binary name of 650 * the class specified above. 651 * 652 * <p> Examples: 653 * <blockquote><pre> 654 * String.class.getName() 655 * returns "java.lang.String" 656 * byte.class.getName() 657 * returns "byte" 658 * (new Object[3]).getClass().getName() 659 * returns "[Ljava.lang.Object;" 660 * (new int[3][4][5][6][7][8][9]).getClass().getName() 661 * returns "[[[[[[[I" 662 * </pre></blockquote> 663 * 664 * @return the name of the class or interface 665 * represented by this object. 666 */ 667 public String getName() { 668 String name = this.name; 669 if (name == null) 670 this.name = name = getName0(); 671 return name; 672 } 673 674 // cache the name to reduce the number of calls into the VM 675 private transient String name; 676 private native String getName0(); 677 678 /** 679 * Returns the class loader for the class. Some implementations may use 680 * null to represent the bootstrap class loader. This method will return 681 * null in such implementations if this class was loaded by the bootstrap 682 * class loader. 683 * 684 * <p> If a security manager is present, and the caller's class loader is 685 * not null and the caller's class loader is not the same as or an ancestor of 686 * the class loader for the class whose class loader is requested, then 687 * this method calls the security manager's {@code checkPermission} 688 * method with a {@code RuntimePermission("getClassLoader")} 689 * permission to ensure it's ok to access the class loader for the class. 690 * 691 * <p>If this object 692 * represents a primitive type or void, null is returned. 693 * 694 * @return the class loader that loaded the class or interface 695 * represented by this object. 696 * @throws SecurityException 697 * if a security manager exists and its 698 * {@code checkPermission} method denies 699 * access to the class loader for the class. 700 * @see java.lang.ClassLoader 701 * @see SecurityManager#checkPermission 702 * @see java.lang.RuntimePermission 703 */ 704 @CallerSensitive 705 public ClassLoader getClassLoader() { 706 ClassLoader cl = getClassLoader0(); 707 if (cl == null) 708 return null; 709 SecurityManager sm = System.getSecurityManager(); 710 if (sm != null) { 711 ClassLoader.checkClassLoaderPermission(cl, Reflection.getCallerClass()); 712 } 713 return cl; 714 } 715 716 // Package-private to allow ClassLoader access 717 ClassLoader getClassLoader0() { return classLoader; } 718 719 // Initialized in JVM not by private constructor 720 // This field is filtered from reflection access, i.e. getDeclaredField 721 // will throw NoSuchFieldException 722 private final ClassLoader classLoader; 723 724 /** 725 * Returns an array of {@code TypeVariable} objects that represent the 726 * type variables declared by the generic declaration represented by this 727 * {@code GenericDeclaration} object, in declaration order. Returns an 728 * array of length 0 if the underlying generic declaration declares no type 729 * variables. 730 * 731 * @return an array of {@code TypeVariable} objects that represent 732 * the type variables declared by this generic declaration 733 * @throws java.lang.reflect.GenericSignatureFormatError if the generic 734 * signature of this generic declaration does not conform to 735 * the format specified in 736 * <cite>The Java™ Virtual Machine Specification</cite> 737 * @since 1.5 738 */ 739 @SuppressWarnings("unchecked") 740 public TypeVariable<Class<T>>[] getTypeParameters() { 741 ClassRepository info = getGenericInfo(); 742 if (info != null) 743 return (TypeVariable<Class<T>>[])info.getTypeParameters(); 744 else 745 return (TypeVariable<Class<T>>[])new TypeVariable<?>[0]; 746 } 747 748 749 /** 750 * Returns the {@code Class} representing the direct superclass of the 751 * entity (class, interface, primitive type or void) represented by 752 * this {@code Class}. If this {@code Class} represents either the 753 * {@code Object} class, an interface, a primitive type, or void, then 754 * null is returned. If this object represents an array class then the 755 * {@code Class} object representing the {@code Object} class is 756 * returned. 757 * 758 * @return the direct superclass of the class represented by this object 759 */ 760 @HotSpotIntrinsicCandidate 761 public native Class<? super T> getSuperclass(); 762 763 764 /** 765 * Returns the {@code Type} representing the direct superclass of 766 * the entity (class, interface, primitive type or void) represented by 767 * this {@code Class}. 768 * 769 * <p>If the superclass is a parameterized type, the {@code Type} 770 * object returned must accurately reflect the actual type 771 * parameters used in the source code. The parameterized type 772 * representing the superclass is created if it had not been 773 * created before. See the declaration of {@link 774 * java.lang.reflect.ParameterizedType ParameterizedType} for the 775 * semantics of the creation process for parameterized types. If 776 * this {@code Class} represents either the {@code Object} 777 * class, an interface, a primitive type, or void, then null is 778 * returned. If this object represents an array class then the 779 * {@code Class} object representing the {@code Object} class is 780 * returned. 781 * 782 * @throws java.lang.reflect.GenericSignatureFormatError if the generic 783 * class signature does not conform to the format specified in 784 * <cite>The Java™ Virtual Machine Specification</cite> 785 * @throws TypeNotPresentException if the generic superclass 786 * refers to a non-existent type declaration 787 * @throws java.lang.reflect.MalformedParameterizedTypeException if the 788 * generic superclass refers to a parameterized type that cannot be 789 * instantiated for any reason 790 * @return the direct superclass of the class represented by this object 791 * @since 1.5 792 */ 793 public Type getGenericSuperclass() { 794 ClassRepository info = getGenericInfo(); 795 if (info == null) { 796 return getSuperclass(); 797 } 798 799 // Historical irregularity: 800 // Generic signature marks interfaces with superclass = Object 801 // but this API returns null for interfaces 802 if (isInterface()) { 803 return null; 804 } 805 806 return info.getSuperclass(); 807 } 808 809 /** 810 * Gets the package for this class. The class loader of this class is used 811 * to find the package. If the class was loaded by the bootstrap class 812 * loader the set of packages loaded from CLASSPATH is searched to find the 813 * package of the class. Null is returned if no package object was created 814 * by the class loader of this class. 815 * 816 * <p> Packages have attributes for versions and specifications only if the 817 * information was defined in the manifests that accompany the classes, and 818 * if the class loader created the package instance with the attributes 819 * from the manifest. 820 * 821 * @return the package of the class, or null if no package 822 * information is available from the archive or codebase. 823 */ 824 public Package getPackage() { 825 return Package.getPackage(this); 826 } 827 828 829 /** 830 * Returns the interfaces directly implemented by the class or interface 831 * represented by this object. 832 * 833 * <p>If this object represents a class, the return value is an array 834 * containing objects representing all interfaces directly implemented by 835 * the class. The order of the interface objects in the array corresponds 836 * to the order of the interface names in the {@code implements} clause of 837 * the declaration of the class represented by this object. For example, 838 * given the declaration: 839 * <blockquote> 840 * {@code class Shimmer implements FloorWax, DessertTopping { ... }} 841 * </blockquote> 842 * suppose the value of {@code s} is an instance of 843 * {@code Shimmer}; the value of the expression: 844 * <blockquote> 845 * {@code s.getClass().getInterfaces()[0]} 846 * </blockquote> 847 * is the {@code Class} object that represents interface 848 * {@code FloorWax}; and the value of: 849 * <blockquote> 850 * {@code s.getClass().getInterfaces()[1]} 851 * </blockquote> 852 * is the {@code Class} object that represents interface 853 * {@code DessertTopping}. 854 * 855 * <p>If this object represents an interface, the array contains objects 856 * representing all interfaces directly extended by the interface. The 857 * order of the interface objects in the array corresponds to the order of 858 * the interface names in the {@code extends} clause of the declaration of 859 * the interface represented by this object. 860 * 861 * <p>If this object represents a class or interface that implements no 862 * interfaces, the method returns an array of length 0. 863 * 864 * <p>If this object represents a primitive type or void, the method 865 * returns an array of length 0. 866 * 867 * <p>If this {@code Class} object represents an array type, the 868 * interfaces {@code Cloneable} and {@code java.io.Serializable} are 869 * returned in that order. 870 * 871 * @return an array of interfaces directly implemented by this class 872 */ 873 public Class<?>[] getInterfaces() { 874 ReflectionData<T> rd = reflectionData(); 875 if (rd == null) { 876 // no cloning required 877 return getInterfaces0(); 878 } else { 879 Class<?>[] interfaces = rd.interfaces; 880 if (interfaces == null) { 881 interfaces = getInterfaces0(); 882 rd.interfaces = interfaces; 883 } 884 // defensively copy before handing over to user code 885 return interfaces.clone(); 886 } 887 } 888 889 private native Class<?>[] getInterfaces0(); 890 891 /** 892 * Returns the {@code Type}s representing the interfaces 893 * directly implemented by the class or interface represented by 894 * this object. 895 * 896 * <p>If a superinterface is a parameterized type, the 897 * {@code Type} object returned for it must accurately reflect 898 * the actual type parameters used in the source code. The 899 * parameterized type representing each superinterface is created 900 * if it had not been created before. See the declaration of 901 * {@link java.lang.reflect.ParameterizedType ParameterizedType} 902 * for the semantics of the creation process for parameterized 903 * types. 904 * 905 * <p>If this object represents a class, the return value is an array 906 * containing objects representing all interfaces directly implemented by 907 * the class. The order of the interface objects in the array corresponds 908 * to the order of the interface names in the {@code implements} clause of 909 * the declaration of the class represented by this object. 910 * 911 * <p>If this object represents an interface, the array contains objects 912 * representing all interfaces directly extended by the interface. The 913 * order of the interface objects in the array corresponds to the order of 914 * the interface names in the {@code extends} clause of the declaration of 915 * the interface represented by this object. 916 * 917 * <p>If this object represents a class or interface that implements no 918 * interfaces, the method returns an array of length 0. 919 * 920 * <p>If this object represents a primitive type or void, the method 921 * returns an array of length 0. 922 * 923 * <p>If this {@code Class} object represents an array type, the 924 * interfaces {@code Cloneable} and {@code java.io.Serializable} are 925 * returned in that order. 926 * 927 * @throws java.lang.reflect.GenericSignatureFormatError 928 * if the generic class signature does not conform to the format 929 * specified in 930 * <cite>The Java™ Virtual Machine Specification</cite> 931 * @throws TypeNotPresentException if any of the generic 932 * superinterfaces refers to a non-existent type declaration 933 * @throws java.lang.reflect.MalformedParameterizedTypeException 934 * if any of the generic superinterfaces refer to a parameterized 935 * type that cannot be instantiated for any reason 936 * @return an array of interfaces directly implemented by this class 937 * @since 1.5 938 */ 939 public Type[] getGenericInterfaces() { 940 ClassRepository info = getGenericInfo(); 941 return (info == null) ? getInterfaces() : info.getSuperInterfaces(); 942 } 943 944 945 /** 946 * Returns the {@code Class} representing the component type of an 947 * array. If this class does not represent an array class this method 948 * returns null. 949 * 950 * @return the {@code Class} representing the component type of this 951 * class if this class is an array 952 * @see java.lang.reflect.Array 953 * @since 1.1 954 */ 955 public Class<?> getComponentType() { 956 // Only return for array types. Storage may be reused for Class for instance types. 957 if (isArray()) { 958 return componentType; 959 } else { 960 return null; 961 } 962 } 963 964 private final Class<?> componentType; 965 966 967 /** 968 * Returns the Java language modifiers for this class or interface, encoded 969 * in an integer. The modifiers consist of the Java Virtual Machine's 970 * constants for {@code public}, {@code protected}, 971 * {@code private}, {@code final}, {@code static}, 972 * {@code abstract} and {@code interface}; they should be decoded 973 * using the methods of class {@code Modifier}. 974 * 975 * <p> If the underlying class is an array class, then its 976 * {@code public}, {@code private} and {@code protected} 977 * modifiers are the same as those of its component type. If this 978 * {@code Class} represents a primitive type or void, its 979 * {@code public} modifier is always {@code true}, and its 980 * {@code protected} and {@code private} modifiers are always 981 * {@code false}. If this object represents an array class, a 982 * primitive type or void, then its {@code final} modifier is always 983 * {@code true} and its interface modifier is always 984 * {@code false}. The values of its other modifiers are not determined 985 * by this specification. 986 * 987 * <p> The modifier encodings are defined in <em>The Java Virtual Machine 988 * Specification</em>, table 4.1. 989 * 990 * @return the {@code int} representing the modifiers for this class 991 * @see java.lang.reflect.Modifier 992 * @since 1.1 993 */ 994 @HotSpotIntrinsicCandidate 995 public native int getModifiers(); 996 997 998 /** 999 * Gets the signers of this class. 1000 * 1001 * @return the signers of this class, or null if there are no signers. In 1002 * particular, this method returns null if this object represents 1003 * a primitive type or void. 1004 * @since 1.1 1005 */ 1006 public native Object[] getSigners(); 1007 1008 1009 /** 1010 * Set the signers of this class. 1011 */ 1012 native void setSigners(Object[] signers); 1013 1014 1015 /** 1016 * If this {@code Class} object represents a local or anonymous 1017 * class within a method, returns a {@link 1018 * java.lang.reflect.Method Method} object representing the 1019 * immediately enclosing method of the underlying class. Returns 1020 * {@code null} otherwise. 1021 * 1022 * In particular, this method returns {@code null} if the underlying 1023 * class is a local or anonymous class immediately enclosed by a type 1024 * declaration, instance initializer or static initializer. 1025 * 1026 * @return the immediately enclosing method of the underlying class, if 1027 * that class is a local or anonymous class; otherwise {@code null}. 1028 * 1029 * @throws SecurityException 1030 * If a security manager, <i>s</i>, is present and any of the 1031 * following conditions is met: 1032 * 1033 * <ul> 1034 * 1035 * <li> the caller's class loader is not the same as the 1036 * class loader of the enclosing class and invocation of 1037 * {@link SecurityManager#checkPermission 1038 * s.checkPermission} method with 1039 * {@code RuntimePermission("accessDeclaredMembers")} 1040 * denies access to the methods within the enclosing class 1041 * 1042 * <li> the caller's class loader is not the same as or an 1043 * ancestor of the class loader for the enclosing class and 1044 * invocation of {@link SecurityManager#checkPackageAccess 1045 * s.checkPackageAccess()} denies access to the package 1046 * of the enclosing class 1047 * 1048 * </ul> 1049 * @since 1.5 1050 */ 1051 @CallerSensitive 1052 public Method getEnclosingMethod() throws SecurityException { 1053 EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo(); 1054 1055 if (enclosingInfo == null) 1056 return null; 1057 else { 1058 if (!enclosingInfo.isMethod()) 1059 return null; 1060 1061 MethodRepository typeInfo = MethodRepository.make(enclosingInfo.getDescriptor(), 1062 getFactory()); 1063 Class<?> returnType = toClass(typeInfo.getReturnType()); 1064 Type [] parameterTypes = typeInfo.getParameterTypes(); 1065 Class<?>[] parameterClasses = new Class<?>[parameterTypes.length]; 1066 1067 // Convert Types to Classes; returned types *should* 1068 // be class objects since the methodDescriptor's used 1069 // don't have generics information 1070 for(int i = 0; i < parameterClasses.length; i++) 1071 parameterClasses[i] = toClass(parameterTypes[i]); 1072 1073 // Perform access check 1074 final Class<?> enclosingCandidate = enclosingInfo.getEnclosingClass(); 1075 enclosingCandidate.checkMemberAccess(Member.DECLARED, 1076 Reflection.getCallerClass(), true); 1077 // Client is ok to access declared methods but j.l.Class might not be. 1078 Method[] candidates = AccessController.doPrivileged( 1079 new PrivilegedAction<>() { 1080 @Override 1081 public Method[] run() { 1082 return enclosingCandidate.getDeclaredMethods(); 1083 } 1084 }); 1085 /* 1086 * Loop over all declared methods; match method name, 1087 * number of and type of parameters, *and* return 1088 * type. Matching return type is also necessary 1089 * because of covariant returns, etc. 1090 */ 1091 for(Method m: candidates) { 1092 if (m.getName().equals(enclosingInfo.getName()) ) { 1093 Class<?>[] candidateParamClasses = m.getParameterTypes(); 1094 if (candidateParamClasses.length == parameterClasses.length) { 1095 boolean matches = true; 1096 for(int i = 0; i < candidateParamClasses.length; i++) { 1097 if (!candidateParamClasses[i].equals(parameterClasses[i])) { 1098 matches = false; 1099 break; 1100 } 1101 } 1102 1103 if (matches) { // finally, check return type 1104 if (m.getReturnType().equals(returnType) ) 1105 return m; 1106 } 1107 } 1108 } 1109 } 1110 1111 throw new InternalError("Enclosing method not found"); 1112 } 1113 } 1114 1115 private native Object[] getEnclosingMethod0(); 1116 1117 private EnclosingMethodInfo getEnclosingMethodInfo() { 1118 Object[] enclosingInfo = getEnclosingMethod0(); 1119 if (enclosingInfo == null) 1120 return null; 1121 else { 1122 return new EnclosingMethodInfo(enclosingInfo); 1123 } 1124 } 1125 1126 private final static class EnclosingMethodInfo { 1127 private Class<?> enclosingClass; 1128 private String name; 1129 private String descriptor; 1130 1131 private EnclosingMethodInfo(Object[] enclosingInfo) { 1132 if (enclosingInfo.length != 3) 1133 throw new InternalError("Malformed enclosing method information"); 1134 try { 1135 // The array is expected to have three elements: 1136 1137 // the immediately enclosing class 1138 enclosingClass = (Class<?>) enclosingInfo[0]; 1139 assert(enclosingClass != null); 1140 1141 // the immediately enclosing method or constructor's 1142 // name (can be null). 1143 name = (String) enclosingInfo[1]; 1144 1145 // the immediately enclosing method or constructor's 1146 // descriptor (null iff name is). 1147 descriptor = (String) enclosingInfo[2]; 1148 assert((name != null && descriptor != null) || name == descriptor); 1149 } catch (ClassCastException cce) { 1150 throw new InternalError("Invalid type in enclosing method information", cce); 1151 } 1152 } 1153 1154 boolean isPartial() { 1155 return enclosingClass == null || name == null || descriptor == null; 1156 } 1157 1158 boolean isConstructor() { return !isPartial() && "<init>".equals(name); } 1159 1160 boolean isMethod() { return !isPartial() && !isConstructor() && !"<clinit>".equals(name); } 1161 1162 Class<?> getEnclosingClass() { return enclosingClass; } 1163 1164 String getName() { return name; } 1165 1166 String getDescriptor() { return descriptor; } 1167 1168 } 1169 1170 private static Class<?> toClass(Type o) { 1171 if (o instanceof GenericArrayType) 1172 return Array.newInstance(toClass(((GenericArrayType)o).getGenericComponentType()), 1173 0) 1174 .getClass(); 1175 return (Class<?>)o; 1176 } 1177 1178 /** 1179 * If this {@code Class} object represents a local or anonymous 1180 * class within a constructor, returns a {@link 1181 * java.lang.reflect.Constructor Constructor} object representing 1182 * the immediately enclosing constructor of the underlying 1183 * class. Returns {@code null} otherwise. In particular, this 1184 * method returns {@code null} if the underlying class is a local 1185 * or anonymous class immediately enclosed by a type declaration, 1186 * instance initializer or static initializer. 1187 * 1188 * @return the immediately enclosing constructor of the underlying class, if 1189 * that class is a local or anonymous class; otherwise {@code null}. 1190 * @throws SecurityException 1191 * If a security manager, <i>s</i>, is present and any of the 1192 * following conditions is met: 1193 * 1194 * <ul> 1195 * 1196 * <li> the caller's class loader is not the same as the 1197 * class loader of the enclosing class and invocation of 1198 * {@link SecurityManager#checkPermission 1199 * s.checkPermission} method with 1200 * {@code RuntimePermission("accessDeclaredMembers")} 1201 * denies access to the constructors within the enclosing class 1202 * 1203 * <li> the caller's class loader is not the same as or an 1204 * ancestor of the class loader for the enclosing class and 1205 * invocation of {@link SecurityManager#checkPackageAccess 1206 * s.checkPackageAccess()} denies access to the package 1207 * of the enclosing class 1208 * 1209 * </ul> 1210 * @since 1.5 1211 */ 1212 @CallerSensitive 1213 public Constructor<?> getEnclosingConstructor() throws SecurityException { 1214 EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo(); 1215 1216 if (enclosingInfo == null) 1217 return null; 1218 else { 1219 if (!enclosingInfo.isConstructor()) 1220 return null; 1221 1222 ConstructorRepository typeInfo = ConstructorRepository.make(enclosingInfo.getDescriptor(), 1223 getFactory()); 1224 Type [] parameterTypes = typeInfo.getParameterTypes(); 1225 Class<?>[] parameterClasses = new Class<?>[parameterTypes.length]; 1226 1227 // Convert Types to Classes; returned types *should* 1228 // be class objects since the methodDescriptor's used 1229 // don't have generics information 1230 for(int i = 0; i < parameterClasses.length; i++) 1231 parameterClasses[i] = toClass(parameterTypes[i]); 1232 1233 // Perform access check 1234 final Class<?> enclosingCandidate = enclosingInfo.getEnclosingClass(); 1235 enclosingCandidate.checkMemberAccess(Member.DECLARED, 1236 Reflection.getCallerClass(), true); 1237 // Client is ok to access declared methods but j.l.Class might not be. 1238 Constructor<?>[] candidates = AccessController.doPrivileged( 1239 new PrivilegedAction<>() { 1240 @Override 1241 public Constructor<?>[] run() { 1242 return enclosingCandidate.getDeclaredConstructors(); 1243 } 1244 }); 1245 /* 1246 * Loop over all declared constructors; match number 1247 * of and type of parameters. 1248 */ 1249 for(Constructor<?> c: candidates) { 1250 Class<?>[] candidateParamClasses = c.getParameterTypes(); 1251 if (candidateParamClasses.length == parameterClasses.length) { 1252 boolean matches = true; 1253 for(int i = 0; i < candidateParamClasses.length; i++) { 1254 if (!candidateParamClasses[i].equals(parameterClasses[i])) { 1255 matches = false; 1256 break; 1257 } 1258 } 1259 1260 if (matches) 1261 return c; 1262 } 1263 } 1264 1265 throw new InternalError("Enclosing constructor not found"); 1266 } 1267 } 1268 1269 1270 /** 1271 * If the class or interface represented by this {@code Class} object 1272 * is a member of another class, returns the {@code Class} object 1273 * representing the class in which it was declared. This method returns 1274 * null if this class or interface is not a member of any other class. If 1275 * this {@code Class} object represents an array class, a primitive 1276 * type, or void,then this method returns null. 1277 * 1278 * @return the declaring class for this class 1279 * @throws SecurityException 1280 * If a security manager, <i>s</i>, is present and the caller's 1281 * class loader is not the same as or an ancestor of the class 1282 * loader for the declaring class and invocation of {@link 1283 * SecurityManager#checkPackageAccess s.checkPackageAccess()} 1284 * denies access to the package of the declaring class 1285 * @since 1.1 1286 */ 1287 @CallerSensitive 1288 public Class<?> getDeclaringClass() throws SecurityException { 1289 final Class<?> candidate = getDeclaringClass0(); 1290 1291 if (candidate != null) 1292 candidate.checkPackageAccess( 1293 ClassLoader.getClassLoader(Reflection.getCallerClass()), true); 1294 return candidate; 1295 } 1296 1297 private native Class<?> getDeclaringClass0(); 1298 1299 1300 /** 1301 * Returns the immediately enclosing class of the underlying 1302 * class. If the underlying class is a top level class this 1303 * method returns {@code null}. 1304 * @return the immediately enclosing class of the underlying class 1305 * @exception SecurityException 1306 * If a security manager, <i>s</i>, is present and the caller's 1307 * class loader is not the same as or an ancestor of the class 1308 * loader for the enclosing class and invocation of {@link 1309 * SecurityManager#checkPackageAccess s.checkPackageAccess()} 1310 * denies access to the package of the enclosing class 1311 * @since 1.5 1312 */ 1313 @CallerSensitive 1314 public Class<?> getEnclosingClass() throws SecurityException { 1315 // There are five kinds of classes (or interfaces): 1316 // a) Top level classes 1317 // b) Nested classes (static member classes) 1318 // c) Inner classes (non-static member classes) 1319 // d) Local classes (named classes declared within a method) 1320 // e) Anonymous classes 1321 1322 1323 // JVM Spec 4.7.7: A class must have an EnclosingMethod 1324 // attribute if and only if it is a local class or an 1325 // anonymous class. 1326 EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo(); 1327 Class<?> enclosingCandidate; 1328 1329 if (enclosingInfo == null) { 1330 // This is a top level or a nested class or an inner class (a, b, or c) 1331 enclosingCandidate = getDeclaringClass(); 1332 } else { 1333 Class<?> enclosingClass = enclosingInfo.getEnclosingClass(); 1334 // This is a local class or an anonymous class (d or e) 1335 if (enclosingClass == this || enclosingClass == null) 1336 throw new InternalError("Malformed enclosing method information"); 1337 else 1338 enclosingCandidate = enclosingClass; 1339 } 1340 1341 if (enclosingCandidate != null) 1342 enclosingCandidate.checkPackageAccess( 1343 ClassLoader.getClassLoader(Reflection.getCallerClass()), true); 1344 return enclosingCandidate; 1345 } 1346 1347 /** 1348 * Returns the simple name of the underlying class as given in the 1349 * source code. Returns an empty string if the underlying class is 1350 * anonymous. 1351 * 1352 * <p>The simple name of an array is the simple name of the 1353 * component type with "[]" appended. In particular the simple 1354 * name of an array whose component type is anonymous is "[]". 1355 * 1356 * @return the simple name of the underlying class 1357 * @since 1.5 1358 */ 1359 public String getSimpleName() { 1360 if (isArray()) 1361 return getComponentType().getSimpleName()+"[]"; 1362 1363 String simpleName = getSimpleBinaryName(); 1364 if (simpleName == null) { // top level class 1365 simpleName = getName(); 1366 return simpleName.substring(simpleName.lastIndexOf('.')+1); // strip the package name 1367 } 1368 return simpleName; 1369 } 1370 1371 /** 1372 * Return an informative string for the name of this type. 1373 * 1374 * @return an informative string for the name of this type 1375 * @since 1.8 1376 */ 1377 public String getTypeName() { 1378 if (isArray()) { 1379 try { 1380 Class<?> cl = this; 1381 int dimensions = 0; 1382 while (cl.isArray()) { 1383 dimensions++; 1384 cl = cl.getComponentType(); 1385 } 1386 StringBuilder sb = new StringBuilder(); 1387 sb.append(cl.getName()); 1388 for (int i = 0; i < dimensions; i++) { 1389 sb.append("[]"); 1390 } 1391 return sb.toString(); 1392 } catch (Throwable e) { /*FALLTHRU*/ } 1393 } 1394 return getName(); 1395 } 1396 1397 /** 1398 * Character.isDigit answers {@code true} to some non-ascii 1399 * digits. This one does not. 1400 */ 1401 private static boolean isAsciiDigit(char c) { 1402 return '0' <= c && c <= '9'; 1403 } 1404 1405 /** 1406 * Returns the canonical name of the underlying class as 1407 * defined by the Java Language Specification. Returns null if 1408 * the underlying class does not have a canonical name (i.e., if 1409 * it is a local or anonymous class or an array whose component 1410 * type does not have a canonical name). 1411 * @return the canonical name of the underlying class if it exists, and 1412 * {@code null} otherwise. 1413 * @since 1.5 1414 */ 1415 public String getCanonicalName() { 1416 if (isArray()) { 1417 String canonicalName = getComponentType().getCanonicalName(); 1418 if (canonicalName != null) 1419 return canonicalName + "[]"; 1420 else 1421 return null; 1422 } 1423 if (isLocalOrAnonymousClass()) 1424 return null; 1425 Class<?> enclosingClass = getEnclosingClass(); 1426 if (enclosingClass == null) { // top level class 1427 return getName(); 1428 } else { 1429 String enclosingName = enclosingClass.getCanonicalName(); 1430 if (enclosingName == null) 1431 return null; 1432 return enclosingName + "." + getSimpleName(); 1433 } 1434 } 1435 1436 /** 1437 * Returns {@code true} if and only if the underlying class 1438 * is an anonymous class. 1439 * 1440 * @return {@code true} if and only if this class is an anonymous class. 1441 * @since 1.5 1442 */ 1443 public boolean isAnonymousClass() { 1444 return "".equals(getSimpleName()); 1445 } 1446 1447 /** 1448 * Returns {@code true} if and only if the underlying class 1449 * is a local class. 1450 * 1451 * @return {@code true} if and only if this class is a local class. 1452 * @since 1.5 1453 */ 1454 public boolean isLocalClass() { 1455 return isLocalOrAnonymousClass() && !isAnonymousClass(); 1456 } 1457 1458 /** 1459 * Returns {@code true} if and only if the underlying class 1460 * is a member class. 1461 * 1462 * @return {@code true} if and only if this class is a member class. 1463 * @since 1.5 1464 */ 1465 public boolean isMemberClass() { 1466 return getSimpleBinaryName() != null && !isLocalOrAnonymousClass(); 1467 } 1468 1469 /** 1470 * Returns the "simple binary name" of the underlying class, i.e., 1471 * the binary name without the leading enclosing class name. 1472 * Returns {@code null} if the underlying class is a top level 1473 * class. 1474 */ 1475 private String getSimpleBinaryName() { 1476 Class<?> enclosingClass = getEnclosingClass(); 1477 if (enclosingClass == null) // top level class 1478 return null; 1479 String name = getSimpleBinaryName0(); 1480 if (name == null) // anonymous class 1481 return ""; 1482 return name; 1483 } 1484 1485 private native String getSimpleBinaryName0(); 1486 1487 /** 1488 * Returns {@code true} if this is a local class or an anonymous 1489 * class. Returns {@code false} otherwise. 1490 */ 1491 private boolean isLocalOrAnonymousClass() { 1492 // JVM Spec 4.7.7: A class must have an EnclosingMethod 1493 // attribute if and only if it is a local class or an 1494 // anonymous class. 1495 return getEnclosingMethodInfo() != null; 1496 } 1497 1498 /** 1499 * Returns an array containing {@code Class} objects representing all 1500 * the public classes and interfaces that are members of the class 1501 * represented by this {@code Class} object. This includes public 1502 * class and interface members inherited from superclasses and public class 1503 * and interface members declared by the class. This method returns an 1504 * array of length 0 if this {@code Class} object has no public member 1505 * classes or interfaces. This method also returns an array of length 0 if 1506 * this {@code Class} object represents a primitive type, an array 1507 * class, or void. 1508 * 1509 * @return the array of {@code Class} objects representing the public 1510 * members of this class 1511 * @throws SecurityException 1512 * If a security manager, <i>s</i>, is present and 1513 * the caller's class loader is not the same as or an 1514 * ancestor of the class loader for the current class and 1515 * invocation of {@link SecurityManager#checkPackageAccess 1516 * s.checkPackageAccess()} denies access to the package 1517 * of this class. 1518 * 1519 * @since 1.1 1520 */ 1521 @CallerSensitive 1522 public Class<?>[] getClasses() { 1523 checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), false); 1524 1525 // Privileged so this implementation can look at DECLARED classes, 1526 // something the caller might not have privilege to do. The code here 1527 // is allowed to look at DECLARED classes because (1) it does not hand 1528 // out anything other than public members and (2) public member access 1529 // has already been ok'd by the SecurityManager. 1530 1531 return java.security.AccessController.doPrivileged( 1532 new java.security.PrivilegedAction<>() { 1533 public Class<?>[] run() { 1534 List<Class<?>> list = new ArrayList<>(); 1535 Class<?> currentClass = Class.this; 1536 while (currentClass != null) { 1537 for (Class<?> m : currentClass.getDeclaredClasses()) { 1538 if (Modifier.isPublic(m.getModifiers())) { 1539 list.add(m); 1540 } 1541 } 1542 currentClass = currentClass.getSuperclass(); 1543 } 1544 return list.toArray(new Class<?>[0]); 1545 } 1546 }); 1547 } 1548 1549 1550 /** 1551 * Returns an array containing {@code Field} objects reflecting all 1552 * the accessible public fields of the class or interface represented by 1553 * this {@code Class} object. 1554 * 1555 * <p> If this {@code Class} object represents a class or interface with 1556 * no accessible public fields, then this method returns an array of length 1557 * 0. 1558 * 1559 * <p> If this {@code Class} object represents a class, then this method 1560 * returns the public fields of the class and of all its superclasses and 1561 * superinterfaces. 1562 * 1563 * <p> If this {@code Class} object represents an interface, then this 1564 * method returns the fields of the interface and of all its 1565 * superinterfaces. 1566 * 1567 * <p> If this {@code Class} object represents an array type, a primitive 1568 * type, or void, then this method returns an array of length 0. 1569 * 1570 * <p> The elements in the returned array are not sorted and are not in any 1571 * particular order. 1572 * 1573 * @return the array of {@code Field} objects representing the 1574 * public fields 1575 * @throws SecurityException 1576 * If a security manager, <i>s</i>, is present and 1577 * the caller's class loader is not the same as or an 1578 * ancestor of the class loader for the current class and 1579 * invocation of {@link SecurityManager#checkPackageAccess 1580 * s.checkPackageAccess()} denies access to the package 1581 * of this class. 1582 * 1583 * @since 1.1 1584 * @jls 8.2 Class Members 1585 * @jls 8.3 Field Declarations 1586 */ 1587 @CallerSensitive 1588 public Field[] getFields() throws SecurityException { 1589 checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true); 1590 return copyFields(privateGetPublicFields(null)); 1591 } 1592 1593 1594 /** 1595 * Returns an array containing {@code Method} objects reflecting all the 1596 * public methods of the class or interface represented by this {@code 1597 * Class} object, including those declared by the class or interface and 1598 * those inherited from superclasses and superinterfaces. 1599 * 1600 * <p> If this {@code Class} object represents a type that has multiple 1601 * public methods with the same name and parameter types, but different 1602 * return types, then the returned array has a {@code Method} object for 1603 * each such method. 1604 * 1605 * <p> If this {@code Class} object represents a type with a class 1606 * initialization method {@code <clinit>}, then the returned array does 1607 * <em>not</em> have a corresponding {@code Method} object. 1608 * 1609 * <p> If this {@code Class} object represents an array type, then the 1610 * returned array has a {@code Method} object for each of the public 1611 * methods inherited by the array type from {@code Object}. It does not 1612 * contain a {@code Method} object for {@code clone()}. 1613 * 1614 * <p> If this {@code Class} object represents an interface then the 1615 * returned array does not contain any implicitly declared methods from 1616 * {@code Object}. Therefore, if no methods are explicitly declared in 1617 * this interface or any of its superinterfaces then the returned array 1618 * has length 0. (Note that a {@code Class} object which represents a class 1619 * always has public methods, inherited from {@code Object}.) 1620 * 1621 * <p> If this {@code Class} object represents a primitive type or void, 1622 * then the returned array has length 0. 1623 * 1624 * <p> Static methods declared in superinterfaces of the class or interface 1625 * represented by this {@code Class} object are not considered members of 1626 * the class or interface. 1627 * 1628 * <p> The elements in the returned array are not sorted and are not in any 1629 * particular order. 1630 * 1631 * @return the array of {@code Method} objects representing the 1632 * public methods of this class 1633 * @throws SecurityException 1634 * If a security manager, <i>s</i>, is present and 1635 * the caller's class loader is not the same as or an 1636 * ancestor of the class loader for the current class and 1637 * invocation of {@link SecurityManager#checkPackageAccess 1638 * s.checkPackageAccess()} denies access to the package 1639 * of this class. 1640 * 1641 * @jls 8.2 Class Members 1642 * @jls 8.4 Method Declarations 1643 * @since 1.1 1644 */ 1645 @CallerSensitive 1646 public Method[] getMethods() throws SecurityException { 1647 checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true); 1648 return copyMethods(privateGetPublicMethods()); 1649 } 1650 1651 1652 /** 1653 * Returns an array containing {@code Constructor} objects reflecting 1654 * all the public constructors of the class represented by this 1655 * {@code Class} object. An array of length 0 is returned if the 1656 * class has no public constructors, or if the class is an array class, or 1657 * if the class reflects a primitive type or void. 1658 * 1659 * Note that while this method returns an array of {@code 1660 * Constructor<T>} objects (that is an array of constructors from 1661 * this class), the return type of this method is {@code 1662 * Constructor<?>[]} and <em>not</em> {@code Constructor<T>[]} as 1663 * might be expected. This less informative return type is 1664 * necessary since after being returned from this method, the 1665 * array could be modified to hold {@code Constructor} objects for 1666 * different classes, which would violate the type guarantees of 1667 * {@code Constructor<T>[]}. 1668 * 1669 * @return the array of {@code Constructor} objects representing the 1670 * public constructors of this class 1671 * @throws SecurityException 1672 * If a security manager, <i>s</i>, is present and 1673 * the caller's class loader is not the same as or an 1674 * ancestor of the class loader for the current class and 1675 * invocation of {@link SecurityManager#checkPackageAccess 1676 * s.checkPackageAccess()} denies access to the package 1677 * of this class. 1678 * 1679 * @since 1.1 1680 */ 1681 @CallerSensitive 1682 public Constructor<?>[] getConstructors() throws SecurityException { 1683 checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true); 1684 return copyConstructors(privateGetDeclaredConstructors(true)); 1685 } 1686 1687 1688 /** 1689 * Returns a {@code Field} object that reflects the specified public member 1690 * field of the class or interface represented by this {@code Class} 1691 * object. The {@code name} parameter is a {@code String} specifying the 1692 * simple name of the desired field. 1693 * 1694 * <p> The field to be reflected is determined by the algorithm that 1695 * follows. Let C be the class or interface represented by this object: 1696 * 1697 * <OL> 1698 * <LI> If C declares a public field with the name specified, that is the 1699 * field to be reflected.</LI> 1700 * <LI> If no field was found in step 1 above, this algorithm is applied 1701 * recursively to each direct superinterface of C. The direct 1702 * superinterfaces are searched in the order they were declared.</LI> 1703 * <LI> If no field was found in steps 1 and 2 above, and C has a 1704 * superclass S, then this algorithm is invoked recursively upon S. 1705 * If C has no superclass, then a {@code NoSuchFieldException} 1706 * is thrown.</LI> 1707 * </OL> 1708 * 1709 * <p> If this {@code Class} object represents an array type, then this 1710 * method does not find the {@code length} field of the array type. 1711 * 1712 * @param name the field name 1713 * @return the {@code Field} object of this class specified by 1714 * {@code name} 1715 * @throws NoSuchFieldException if a field with the specified name is 1716 * not found. 1717 * @throws NullPointerException if {@code name} is {@code null} 1718 * @throws SecurityException 1719 * If a security manager, <i>s</i>, is present and 1720 * the caller's class loader is not the same as or an 1721 * ancestor of the class loader for the current class and 1722 * invocation of {@link SecurityManager#checkPackageAccess 1723 * s.checkPackageAccess()} denies access to the package 1724 * of this class. 1725 * 1726 * @since 1.1 1727 * @jls 8.2 Class Members 1728 * @jls 8.3 Field Declarations 1729 */ 1730 @CallerSensitive 1731 public Field getField(String name) 1732 throws NoSuchFieldException, SecurityException { 1733 checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true); 1734 Field field = getField0(name); 1735 if (field == null) { 1736 throw new NoSuchFieldException(name); 1737 } 1738 return field; 1739 } 1740 1741 1742 /** 1743 * Returns a {@code Method} object that reflects the specified public 1744 * member method of the class or interface represented by this 1745 * {@code Class} object. The {@code name} parameter is a 1746 * {@code String} specifying the simple name of the desired method. The 1747 * {@code parameterTypes} parameter is an array of {@code Class} 1748 * objects that identify the method's formal parameter types, in declared 1749 * order. If {@code parameterTypes} is {@code null}, it is 1750 * treated as if it were an empty array. 1751 * 1752 * <p> If the {@code name} is "{@code <init>}" or "{@code <clinit>}" a 1753 * {@code NoSuchMethodException} is raised. Otherwise, the method to 1754 * be reflected is determined by the algorithm that follows. Let C be the 1755 * class or interface represented by this object: 1756 * <OL> 1757 * <LI> C is searched for a <I>matching method</I>, as defined below. If a 1758 * matching method is found, it is reflected.</LI> 1759 * <LI> If no matching method is found by step 1 then: 1760 * <OL TYPE="a"> 1761 * <LI> If C is a class other than {@code Object}, then this algorithm is 1762 * invoked recursively on the superclass of C.</LI> 1763 * <LI> If C is the class {@code Object}, or if C is an interface, then 1764 * the superinterfaces of C (if any) are searched for a matching 1765 * method. If any such method is found, it is reflected.</LI> 1766 * </OL></LI> 1767 * </OL> 1768 * 1769 * <p> To find a matching method in a class or interface C: If C 1770 * declares exactly one public method with the specified name and exactly 1771 * the same formal parameter types, that is the method reflected. If more 1772 * than one such method is found in C, and one of these methods has a 1773 * return type that is more specific than any of the others, that method is 1774 * reflected; otherwise one of the methods is chosen arbitrarily. 1775 * 1776 * <p>Note that there may be more than one matching method in a 1777 * class because while the Java language forbids a class to 1778 * declare multiple methods with the same signature but different 1779 * return types, the Java virtual machine does not. This 1780 * increased flexibility in the virtual machine can be used to 1781 * implement various language features. For example, covariant 1782 * returns can be implemented with {@linkplain 1783 * java.lang.reflect.Method#isBridge bridge methods}; the bridge 1784 * method and the method being overridden would have the same 1785 * signature but different return types. 1786 * 1787 * <p> If this {@code Class} object represents an array type, then this 1788 * method does not find the {@code clone()} method. 1789 * 1790 * <p> Static methods declared in superinterfaces of the class or interface 1791 * represented by this {@code Class} object are not considered members of 1792 * the class or interface. 1793 * 1794 * @param name the name of the method 1795 * @param parameterTypes the list of parameters 1796 * @return the {@code Method} object that matches the specified 1797 * {@code name} and {@code parameterTypes} 1798 * @throws NoSuchMethodException if a matching method is not found 1799 * or if the name is "<init>"or "<clinit>". 1800 * @throws NullPointerException if {@code name} is {@code null} 1801 * @throws SecurityException 1802 * If a security manager, <i>s</i>, is present and 1803 * the caller's class loader is not the same as or an 1804 * ancestor of the class loader for the current class and 1805 * invocation of {@link SecurityManager#checkPackageAccess 1806 * s.checkPackageAccess()} denies access to the package 1807 * of this class. 1808 * 1809 * @jls 8.2 Class Members 1810 * @jls 8.4 Method Declarations 1811 * @since 1.1 1812 */ 1813 @CallerSensitive 1814 public Method getMethod(String name, Class<?>... parameterTypes) 1815 throws NoSuchMethodException, SecurityException { 1816 checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true); 1817 Method method = getMethod0(name, parameterTypes, true); 1818 if (method == null) { 1819 throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes)); 1820 } 1821 return method; 1822 } 1823 1824 1825 /** 1826 * Returns a {@code Constructor} object that reflects the specified 1827 * public constructor of the class represented by this {@code Class} 1828 * object. The {@code parameterTypes} parameter is an array of 1829 * {@code Class} objects that identify the constructor's formal 1830 * parameter types, in declared order. 1831 * 1832 * If this {@code Class} object represents an inner class 1833 * declared in a non-static context, the formal parameter types 1834 * include the explicit enclosing instance as the first parameter. 1835 * 1836 * <p> The constructor to reflect is the public constructor of the class 1837 * represented by this {@code Class} object whose formal parameter 1838 * types match those specified by {@code parameterTypes}. 1839 * 1840 * @param parameterTypes the parameter array 1841 * @return the {@code Constructor} object of the public constructor that 1842 * matches the specified {@code parameterTypes} 1843 * @throws NoSuchMethodException if a matching method is not found. 1844 * @throws SecurityException 1845 * If a security manager, <i>s</i>, is present and 1846 * the caller's class loader is not the same as or an 1847 * ancestor of the class loader for the current class and 1848 * invocation of {@link SecurityManager#checkPackageAccess 1849 * s.checkPackageAccess()} denies access to the package 1850 * of this class. 1851 * 1852 * @since 1.1 1853 */ 1854 @CallerSensitive 1855 public Constructor<T> getConstructor(Class<?>... parameterTypes) 1856 throws NoSuchMethodException, SecurityException { 1857 checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true); 1858 return getConstructor0(parameterTypes, Member.PUBLIC); 1859 } 1860 1861 1862 /** 1863 * Returns an array of {@code Class} objects reflecting all the 1864 * classes and interfaces declared as members of the class represented by 1865 * this {@code Class} object. This includes public, protected, default 1866 * (package) access, and private classes and interfaces declared by the 1867 * class, but excludes inherited classes and interfaces. This method 1868 * returns an array of length 0 if the class declares no classes or 1869 * interfaces as members, or if this {@code Class} object represents a 1870 * primitive type, an array class, or void. 1871 * 1872 * @return the array of {@code Class} objects representing all the 1873 * declared members of this class 1874 * @throws SecurityException 1875 * If a security manager, <i>s</i>, is present and any of the 1876 * following conditions is met: 1877 * 1878 * <ul> 1879 * 1880 * <li> the caller's class loader is not the same as the 1881 * class loader of this class and invocation of 1882 * {@link SecurityManager#checkPermission 1883 * s.checkPermission} method with 1884 * {@code RuntimePermission("accessDeclaredMembers")} 1885 * denies access to the declared classes within this class 1886 * 1887 * <li> the caller's class loader is not the same as or an 1888 * ancestor of the class loader for the current class and 1889 * invocation of {@link SecurityManager#checkPackageAccess 1890 * s.checkPackageAccess()} denies access to the package 1891 * of this class 1892 * 1893 * </ul> 1894 * 1895 * @since 1.1 1896 */ 1897 @CallerSensitive 1898 public Class<?>[] getDeclaredClasses() throws SecurityException { 1899 checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), false); 1900 return getDeclaredClasses0(); 1901 } 1902 1903 1904 /** 1905 * Returns an array of {@code Field} objects reflecting all the fields 1906 * declared by the class or interface represented by this 1907 * {@code Class} object. This includes public, protected, default 1908 * (package) access, and private fields, but excludes inherited fields. 1909 * 1910 * <p> If this {@code Class} object represents a class or interface with no 1911 * declared fields, then this method returns an array of length 0. 1912 * 1913 * <p> If this {@code Class} object represents an array type, a primitive 1914 * type, or void, then this method returns an array of length 0. 1915 * 1916 * <p> The elements in the returned array are not sorted and are not in any 1917 * particular order. 1918 * 1919 * @return the array of {@code Field} objects representing all the 1920 * declared fields of this class 1921 * @throws SecurityException 1922 * If a security manager, <i>s</i>, is present and any of the 1923 * following conditions is met: 1924 * 1925 * <ul> 1926 * 1927 * <li> the caller's class loader is not the same as the 1928 * class loader of this class and invocation of 1929 * {@link SecurityManager#checkPermission 1930 * s.checkPermission} method with 1931 * {@code RuntimePermission("accessDeclaredMembers")} 1932 * denies access to the declared fields within this class 1933 * 1934 * <li> the caller's class loader is not the same as or an 1935 * ancestor of the class loader for the current class and 1936 * invocation of {@link SecurityManager#checkPackageAccess 1937 * s.checkPackageAccess()} denies access to the package 1938 * of this class 1939 * 1940 * </ul> 1941 * 1942 * @since 1.1 1943 * @jls 8.2 Class Members 1944 * @jls 8.3 Field Declarations 1945 */ 1946 @CallerSensitive 1947 public Field[] getDeclaredFields() throws SecurityException { 1948 checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true); 1949 return copyFields(privateGetDeclaredFields(false)); 1950 } 1951 1952 1953 /** 1954 * 1955 * Returns an array containing {@code Method} objects reflecting all the 1956 * declared methods of the class or interface represented by this {@code 1957 * Class} object, including public, protected, default (package) 1958 * access, and private methods, but excluding inherited methods. 1959 * 1960 * <p> If this {@code Class} object represents a type that has multiple 1961 * declared methods with the same name and parameter types, but different 1962 * return types, then the returned array has a {@code Method} object for 1963 * each such method. 1964 * 1965 * <p> If this {@code Class} object represents a type that has a class 1966 * initialization method {@code <clinit>}, then the returned array does 1967 * <em>not</em> have a corresponding {@code Method} object. 1968 * 1969 * <p> If this {@code Class} object represents a class or interface with no 1970 * declared methods, then the returned array has length 0. 1971 * 1972 * <p> If this {@code Class} object represents an array type, a primitive 1973 * type, or void, then the returned array has length 0. 1974 * 1975 * <p> The elements in the returned array are not sorted and are not in any 1976 * particular order. 1977 * 1978 * @return the array of {@code Method} objects representing all the 1979 * declared methods of this class 1980 * @throws SecurityException 1981 * If a security manager, <i>s</i>, is present and any of the 1982 * following conditions is met: 1983 * 1984 * <ul> 1985 * 1986 * <li> the caller's class loader is not the same as the 1987 * class loader of this class and invocation of 1988 * {@link SecurityManager#checkPermission 1989 * s.checkPermission} method with 1990 * {@code RuntimePermission("accessDeclaredMembers")} 1991 * denies access to the declared methods within this class 1992 * 1993 * <li> the caller's class loader is not the same as or an 1994 * ancestor of the class loader for the current class and 1995 * invocation of {@link SecurityManager#checkPackageAccess 1996 * s.checkPackageAccess()} denies access to the package 1997 * of this class 1998 * 1999 * </ul> 2000 * 2001 * @jls 8.2 Class Members 2002 * @jls 8.4 Method Declarations 2003 * @since 1.1 2004 */ 2005 @CallerSensitive 2006 public Method[] getDeclaredMethods() throws SecurityException { 2007 checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true); 2008 return copyMethods(privateGetDeclaredMethods(false)); 2009 } 2010 2011 2012 /** 2013 * Returns an array of {@code Constructor} objects reflecting all the 2014 * constructors declared by the class represented by this 2015 * {@code Class} object. These are public, protected, default 2016 * (package) access, and private constructors. The elements in the array 2017 * returned are not sorted and are not in any particular order. If the 2018 * class has a default constructor, it is included in the returned array. 2019 * This method returns an array of length 0 if this {@code Class} 2020 * object represents an interface, a primitive type, an array class, or 2021 * void. 2022 * 2023 * <p> See <em>The Java Language Specification</em>, section 8.2. 2024 * 2025 * @return the array of {@code Constructor} objects representing all the 2026 * declared constructors of this class 2027 * @throws SecurityException 2028 * If a security manager, <i>s</i>, is present and any of the 2029 * following conditions is met: 2030 * 2031 * <ul> 2032 * 2033 * <li> the caller's class loader is not the same as the 2034 * class loader of this class and invocation of 2035 * {@link SecurityManager#checkPermission 2036 * s.checkPermission} method with 2037 * {@code RuntimePermission("accessDeclaredMembers")} 2038 * denies access to the declared constructors within this class 2039 * 2040 * <li> the caller's class loader is not the same as or an 2041 * ancestor of the class loader for the current class and 2042 * invocation of {@link SecurityManager#checkPackageAccess 2043 * s.checkPackageAccess()} denies access to the package 2044 * of this class 2045 * 2046 * </ul> 2047 * 2048 * @since 1.1 2049 */ 2050 @CallerSensitive 2051 public Constructor<?>[] getDeclaredConstructors() throws SecurityException { 2052 checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true); 2053 return copyConstructors(privateGetDeclaredConstructors(false)); 2054 } 2055 2056 2057 /** 2058 * Returns a {@code Field} object that reflects the specified declared 2059 * field of the class or interface represented by this {@code Class} 2060 * object. The {@code name} parameter is a {@code String} that specifies 2061 * the simple name of the desired field. 2062 * 2063 * <p> If this {@code Class} object represents an array type, then this 2064 * method does not find the {@code length} field of the array type. 2065 * 2066 * @param name the name of the field 2067 * @return the {@code Field} object for the specified field in this 2068 * class 2069 * @throws NoSuchFieldException if a field with the specified name is 2070 * not found. 2071 * @throws NullPointerException if {@code name} is {@code null} 2072 * @throws SecurityException 2073 * If a security manager, <i>s</i>, is present and any of the 2074 * following conditions is met: 2075 * 2076 * <ul> 2077 * 2078 * <li> the caller's class loader is not the same as the 2079 * class loader of this class and invocation of 2080 * {@link SecurityManager#checkPermission 2081 * s.checkPermission} method with 2082 * {@code RuntimePermission("accessDeclaredMembers")} 2083 * denies access to the declared field 2084 * 2085 * <li> the caller's class loader is not the same as or an 2086 * ancestor of the class loader for the current class and 2087 * invocation of {@link SecurityManager#checkPackageAccess 2088 * s.checkPackageAccess()} denies access to the package 2089 * of this class 2090 * 2091 * </ul> 2092 * 2093 * @since 1.1 2094 * @jls 8.2 Class Members 2095 * @jls 8.3 Field Declarations 2096 */ 2097 @CallerSensitive 2098 public Field getDeclaredField(String name) 2099 throws NoSuchFieldException, SecurityException { 2100 checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true); 2101 Field field = searchFields(privateGetDeclaredFields(false), name); 2102 if (field == null) { 2103 throw new NoSuchFieldException(name); 2104 } 2105 return field; 2106 } 2107 2108 2109 /** 2110 * Returns a {@code Method} object that reflects the specified 2111 * declared method of the class or interface represented by this 2112 * {@code Class} object. The {@code name} parameter is a 2113 * {@code String} that specifies the simple name of the desired 2114 * method, and the {@code parameterTypes} parameter is an array of 2115 * {@code Class} objects that identify the method's formal parameter 2116 * types, in declared order. If more than one method with the same 2117 * parameter types is declared in a class, and one of these methods has a 2118 * return type that is more specific than any of the others, that method is 2119 * returned; otherwise one of the methods is chosen arbitrarily. If the 2120 * name is "<init>"or "<clinit>" a {@code NoSuchMethodException} 2121 * is raised. 2122 * 2123 * <p> If this {@code Class} object represents an array type, then this 2124 * method does not find the {@code clone()} method. 2125 * 2126 * @param name the name of the method 2127 * @param parameterTypes the parameter array 2128 * @return the {@code Method} object for the method of this class 2129 * matching the specified name and parameters 2130 * @throws NoSuchMethodException if a matching method is not found. 2131 * @throws NullPointerException if {@code name} is {@code null} 2132 * @throws SecurityException 2133 * If a security manager, <i>s</i>, is present and any of the 2134 * following conditions is met: 2135 * 2136 * <ul> 2137 * 2138 * <li> the caller's class loader is not the same as the 2139 * class loader of this class and invocation of 2140 * {@link SecurityManager#checkPermission 2141 * s.checkPermission} method with 2142 * {@code RuntimePermission("accessDeclaredMembers")} 2143 * denies access to the declared method 2144 * 2145 * <li> the caller's class loader is not the same as or an 2146 * ancestor of the class loader for the current class and 2147 * invocation of {@link SecurityManager#checkPackageAccess 2148 * s.checkPackageAccess()} denies access to the package 2149 * of this class 2150 * 2151 * </ul> 2152 * 2153 * @jls 8.2 Class Members 2154 * @jls 8.4 Method Declarations 2155 * @since 1.1 2156 */ 2157 @CallerSensitive 2158 public Method getDeclaredMethod(String name, Class<?>... parameterTypes) 2159 throws NoSuchMethodException, SecurityException { 2160 checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true); 2161 Method method = searchMethods(privateGetDeclaredMethods(false), name, parameterTypes); 2162 if (method == null) { 2163 throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes)); 2164 } 2165 return method; 2166 } 2167 2168 2169 /** 2170 * Returns a {@code Constructor} object that reflects the specified 2171 * constructor of the class or interface represented by this 2172 * {@code Class} object. The {@code parameterTypes} parameter is 2173 * an array of {@code Class} objects that identify the constructor's 2174 * formal parameter types, in declared order. 2175 * 2176 * If this {@code Class} object represents an inner class 2177 * declared in a non-static context, the formal parameter types 2178 * include the explicit enclosing instance as the first parameter. 2179 * 2180 * @param parameterTypes the parameter array 2181 * @return The {@code Constructor} object for the constructor with the 2182 * specified parameter list 2183 * @throws NoSuchMethodException if a matching method is not found. 2184 * @throws SecurityException 2185 * If a security manager, <i>s</i>, is present and any of the 2186 * following conditions is met: 2187 * 2188 * <ul> 2189 * 2190 * <li> the caller's class loader is not the same as the 2191 * class loader of this class and invocation of 2192 * {@link SecurityManager#checkPermission 2193 * s.checkPermission} method with 2194 * {@code RuntimePermission("accessDeclaredMembers")} 2195 * denies access to the declared constructor 2196 * 2197 * <li> the caller's class loader is not the same as or an 2198 * ancestor of the class loader for the current class and 2199 * invocation of {@link SecurityManager#checkPackageAccess 2200 * s.checkPackageAccess()} denies access to the package 2201 * of this class 2202 * 2203 * </ul> 2204 * 2205 * @since 1.1 2206 */ 2207 @CallerSensitive 2208 public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes) 2209 throws NoSuchMethodException, SecurityException { 2210 checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true); 2211 return getConstructor0(parameterTypes, Member.DECLARED); 2212 } 2213 2214 /** 2215 * Finds a resource with a given name. The rules for searching resources 2216 * associated with a given class are implemented by the defining 2217 * {@linkplain ClassLoader class loader} of the class. This method 2218 * delegates to this object's class loader. If this object was loaded by 2219 * the bootstrap class loader, the method delegates to {@link 2220 * ClassLoader#getSystemResourceAsStream}. 2221 * 2222 * <p> Before delegation, an absolute resource name is constructed from the 2223 * given resource name using this algorithm: 2224 * 2225 * <ul> 2226 * 2227 * <li> If the {@code name} begins with a {@code '/'} 2228 * (<tt>'\u002f'</tt>), then the absolute name of the resource is the 2229 * portion of the {@code name} following the {@code '/'}. 2230 * 2231 * <li> Otherwise, the absolute name is of the following form: 2232 * 2233 * <blockquote> 2234 * {@code modified_package_name/name} 2235 * </blockquote> 2236 * 2237 * <p> Where the {@code modified_package_name} is the package name of this 2238 * object with {@code '/'} substituted for {@code '.'} 2239 * (<tt>'\u002e'</tt>). 2240 * 2241 * </ul> 2242 * 2243 * @param name name of the desired resource 2244 * @return A {@link java.io.InputStream} object or {@code null} if 2245 * no resource with this name is found 2246 * @throws NullPointerException If {@code name} is {@code null} 2247 * @since 1.1 2248 */ 2249 public InputStream getResourceAsStream(String name) { 2250 name = resolveName(name); 2251 ClassLoader cl = getClassLoader0(); 2252 if (cl==null) { 2253 // A system class. 2254 return ClassLoader.getSystemResourceAsStream(name); 2255 } 2256 return cl.getResourceAsStream(name); 2257 } 2258 2259 /** 2260 * Finds a resource with a given name. The rules for searching resources 2261 * associated with a given class are implemented by the defining 2262 * {@linkplain ClassLoader class loader} of the class. This method 2263 * delegates to this object's class loader. If this object was loaded by 2264 * the bootstrap class loader, the method delegates to {@link 2265 * ClassLoader#getSystemResource}. 2266 * 2267 * <p> Before delegation, an absolute resource name is constructed from the 2268 * given resource name using this algorithm: 2269 * 2270 * <ul> 2271 * 2272 * <li> If the {@code name} begins with a {@code '/'} 2273 * (<tt>'\u002f'</tt>), then the absolute name of the resource is the 2274 * portion of the {@code name} following the {@code '/'}. 2275 * 2276 * <li> Otherwise, the absolute name is of the following form: 2277 * 2278 * <blockquote> 2279 * {@code modified_package_name/name} 2280 * </blockquote> 2281 * 2282 * <p> Where the {@code modified_package_name} is the package name of this 2283 * object with {@code '/'} substituted for {@code '.'} 2284 * (<tt>'\u002e'</tt>). 2285 * 2286 * </ul> 2287 * 2288 * @param name name of the desired resource 2289 * @return A {@link java.net.URL} object or {@code null} if no 2290 * resource with this name is found 2291 * @since 1.1 2292 */ 2293 public java.net.URL getResource(String name) { 2294 name = resolveName(name); 2295 ClassLoader cl = getClassLoader0(); 2296 if (cl==null) { 2297 // A system class. 2298 return ClassLoader.getSystemResource(name); 2299 } 2300 return cl.getResource(name); 2301 } 2302 2303 2304 2305 /** protection domain returned when the internal domain is null */ 2306 private static java.security.ProtectionDomain allPermDomain; 2307 2308 2309 /** 2310 * Returns the {@code ProtectionDomain} of this class. If there is a 2311 * security manager installed, this method first calls the security 2312 * manager's {@code checkPermission} method with a 2313 * {@code RuntimePermission("getProtectionDomain")} permission to 2314 * ensure it's ok to get the 2315 * {@code ProtectionDomain}. 2316 * 2317 * @return the ProtectionDomain of this class 2318 * 2319 * @throws SecurityException 2320 * if a security manager exists and its 2321 * {@code checkPermission} method doesn't allow 2322 * getting the ProtectionDomain. 2323 * 2324 * @see java.security.ProtectionDomain 2325 * @see SecurityManager#checkPermission 2326 * @see java.lang.RuntimePermission 2327 * @since 1.2 2328 */ 2329 public java.security.ProtectionDomain getProtectionDomain() { 2330 SecurityManager sm = System.getSecurityManager(); 2331 if (sm != null) { 2332 sm.checkPermission(SecurityConstants.GET_PD_PERMISSION); 2333 } 2334 java.security.ProtectionDomain pd = getProtectionDomain0(); 2335 if (pd == null) { 2336 if (allPermDomain == null) { 2337 java.security.Permissions perms = 2338 new java.security.Permissions(); 2339 perms.add(SecurityConstants.ALL_PERMISSION); 2340 allPermDomain = 2341 new java.security.ProtectionDomain(null, perms); 2342 } 2343 pd = allPermDomain; 2344 } 2345 return pd; 2346 } 2347 2348 2349 /** 2350 * Returns the ProtectionDomain of this class. 2351 */ 2352 private native java.security.ProtectionDomain getProtectionDomain0(); 2353 2354 /* 2355 * Return the Virtual Machine's Class object for the named 2356 * primitive type. 2357 */ 2358 static native Class<?> getPrimitiveClass(String name); 2359 2360 /* 2361 * Check if client is allowed to access members. If access is denied, 2362 * throw a SecurityException. 2363 * 2364 * This method also enforces package access. 2365 * 2366 * <p> Default policy: allow all clients access with normal Java access 2367 * control. 2368 */ 2369 private void checkMemberAccess(int which, Class<?> caller, boolean checkProxyInterfaces) { 2370 final SecurityManager s = System.getSecurityManager(); 2371 if (s != null) { 2372 /* Default policy allows access to all {@link Member#PUBLIC} members, 2373 * as well as access to classes that have the same class loader as the caller. 2374 * In all other cases, it requires RuntimePermission("accessDeclaredMembers") 2375 * permission. 2376 */ 2377 final ClassLoader ccl = ClassLoader.getClassLoader(caller); 2378 final ClassLoader cl = getClassLoader0(); 2379 if (which != Member.PUBLIC) { 2380 if (ccl != cl) { 2381 s.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION); 2382 } 2383 } 2384 this.checkPackageAccess(ccl, checkProxyInterfaces); 2385 } 2386 } 2387 2388 /* 2389 * Checks if a client loaded in ClassLoader ccl is allowed to access this 2390 * class under the current package access policy. If access is denied, 2391 * throw a SecurityException. 2392 */ 2393 private void checkPackageAccess(final ClassLoader ccl, boolean checkProxyInterfaces) { 2394 final SecurityManager s = System.getSecurityManager(); 2395 if (s != null) { 2396 final ClassLoader cl = getClassLoader0(); 2397 2398 if (ReflectUtil.needsPackageAccessCheck(ccl, cl)) { 2399 String name = this.getName(); 2400 int i = name.lastIndexOf('.'); 2401 if (i != -1) { 2402 // skip the package access check on a proxy class in default proxy package 2403 String pkg = name.substring(0, i); 2404 if (!Proxy.isProxyClass(this) || ReflectUtil.isNonPublicProxyClass(this)) { 2405 s.checkPackageAccess(pkg); 2406 } 2407 } 2408 } 2409 // check package access on the proxy interfaces 2410 if (checkProxyInterfaces && Proxy.isProxyClass(this)) { 2411 ReflectUtil.checkProxyPackageAccess(ccl, this.getInterfaces()); 2412 } 2413 } 2414 } 2415 2416 /** 2417 * Add a package name prefix if the name is not absolute Remove leading "/" 2418 * if name is absolute 2419 */ 2420 private String resolveName(String name) { 2421 if (name == null) { 2422 return name; 2423 } 2424 if (!name.startsWith("/")) { 2425 Class<?> c = this; 2426 while (c.isArray()) { 2427 c = c.getComponentType(); 2428 } 2429 String baseName = c.getName(); 2430 int index = baseName.lastIndexOf('.'); 2431 if (index != -1) { 2432 name = baseName.substring(0, index).replace('.', '/') 2433 +"/"+name; 2434 } 2435 } else { 2436 name = name.substring(1); 2437 } 2438 return name; 2439 } 2440 2441 /** 2442 * Atomic operations support. 2443 */ 2444 private static class Atomic { 2445 // initialize Unsafe machinery here, since we need to call Class.class instance method 2446 // and have to avoid calling it in the static initializer of the Class class... 2447 private static final Unsafe unsafe = Unsafe.getUnsafe(); 2448 // offset of Class.reflectionData instance field 2449 private static final long reflectionDataOffset; 2450 // offset of Class.annotationType instance field 2451 private static final long annotationTypeOffset; 2452 // offset of Class.annotationData instance field 2453 private static final long annotationDataOffset; 2454 2455 static { 2456 Field[] fields = Class.class.getDeclaredFields0(false); // bypass caches 2457 reflectionDataOffset = objectFieldOffset(fields, "reflectionData"); 2458 annotationTypeOffset = objectFieldOffset(fields, "annotationType"); 2459 annotationDataOffset = objectFieldOffset(fields, "annotationData"); 2460 } 2461 2462 private static long objectFieldOffset(Field[] fields, String fieldName) { 2463 Field field = searchFields(fields, fieldName); 2464 if (field == null) { 2465 throw new Error("No " + fieldName + " field found in java.lang.Class"); 2466 } 2467 return unsafe.objectFieldOffset(field); 2468 } 2469 2470 static <T> boolean casReflectionData(Class<?> clazz, 2471 SoftReference<ReflectionData<T>> oldData, 2472 SoftReference<ReflectionData<T>> newData) { 2473 return unsafe.compareAndSwapObject(clazz, reflectionDataOffset, oldData, newData); 2474 } 2475 2476 static <T> boolean casAnnotationType(Class<?> clazz, 2477 AnnotationType oldType, 2478 AnnotationType newType) { 2479 return unsafe.compareAndSwapObject(clazz, annotationTypeOffset, oldType, newType); 2480 } 2481 2482 static <T> boolean casAnnotationData(Class<?> clazz, 2483 AnnotationData oldData, 2484 AnnotationData newData) { 2485 return unsafe.compareAndSwapObject(clazz, annotationDataOffset, oldData, newData); 2486 } 2487 } 2488 2489 /** 2490 * Reflection support. 2491 */ 2492 2493 // Caches for certain reflective results 2494 private static boolean useCaches = true; 2495 2496 // reflection data that might get invalidated when JVM TI RedefineClasses() is called 2497 private static class ReflectionData<T> { 2498 volatile Field[] declaredFields; 2499 volatile Field[] publicFields; 2500 volatile Method[] declaredMethods; 2501 volatile Method[] publicMethods; 2502 volatile Constructor<T>[] declaredConstructors; 2503 volatile Constructor<T>[] publicConstructors; 2504 // Intermediate results for getFields and getMethods 2505 volatile Field[] declaredPublicFields; 2506 volatile Method[] declaredPublicMethods; 2507 volatile Class<?>[] interfaces; 2508 2509 // Value of classRedefinedCount when we created this ReflectionData instance 2510 final int redefinedCount; 2511 2512 ReflectionData(int redefinedCount) { 2513 this.redefinedCount = redefinedCount; 2514 } 2515 } 2516 2517 private volatile transient SoftReference<ReflectionData<T>> reflectionData; 2518 2519 // Incremented by the VM on each call to JVM TI RedefineClasses() 2520 // that redefines this class or a superclass. 2521 private volatile transient int classRedefinedCount = 0; 2522 2523 // Lazily create and cache ReflectionData 2524 private ReflectionData<T> reflectionData() { 2525 SoftReference<ReflectionData<T>> reflectionData = this.reflectionData; 2526 int classRedefinedCount = this.classRedefinedCount; 2527 ReflectionData<T> rd; 2528 if (useCaches && 2529 reflectionData != null && 2530 (rd = reflectionData.get()) != null && 2531 rd.redefinedCount == classRedefinedCount) { 2532 return rd; 2533 } 2534 // else no SoftReference or cleared SoftReference or stale ReflectionData 2535 // -> create and replace new instance 2536 return newReflectionData(reflectionData, classRedefinedCount); 2537 } 2538 2539 private ReflectionData<T> newReflectionData(SoftReference<ReflectionData<T>> oldReflectionData, 2540 int classRedefinedCount) { 2541 if (!useCaches) return null; 2542 2543 while (true) { 2544 ReflectionData<T> rd = new ReflectionData<>(classRedefinedCount); 2545 // try to CAS it... 2546 if (Atomic.casReflectionData(this, oldReflectionData, new SoftReference<>(rd))) { 2547 return rd; 2548 } 2549 // else retry 2550 oldReflectionData = this.reflectionData; 2551 classRedefinedCount = this.classRedefinedCount; 2552 if (oldReflectionData != null && 2553 (rd = oldReflectionData.get()) != null && 2554 rd.redefinedCount == classRedefinedCount) { 2555 return rd; 2556 } 2557 } 2558 } 2559 2560 // Generic signature handling 2561 private native String getGenericSignature0(); 2562 2563 // Generic info repository; lazily initialized 2564 private volatile transient ClassRepository genericInfo; 2565 2566 // accessor for factory 2567 private GenericsFactory getFactory() { 2568 // create scope and factory 2569 return CoreReflectionFactory.make(this, ClassScope.make(this)); 2570 } 2571 2572 // accessor for generic info repository; 2573 // generic info is lazily initialized 2574 private ClassRepository getGenericInfo() { 2575 ClassRepository genericInfo = this.genericInfo; 2576 if (genericInfo == null) { 2577 String signature = getGenericSignature0(); 2578 if (signature == null) { 2579 genericInfo = ClassRepository.NONE; 2580 } else { 2581 genericInfo = ClassRepository.make(signature, getFactory()); 2582 } 2583 this.genericInfo = genericInfo; 2584 } 2585 return (genericInfo != ClassRepository.NONE) ? genericInfo : null; 2586 } 2587 2588 // Annotations handling 2589 native byte[] getRawAnnotations(); 2590 // Since 1.8 2591 native byte[] getRawTypeAnnotations(); 2592 static byte[] getExecutableTypeAnnotationBytes(Executable ex) { 2593 return getReflectionFactory().getExecutableTypeAnnotationBytes(ex); 2594 } 2595 2596 native ConstantPool getConstantPool(); 2597 2598 // 2599 // 2600 // java.lang.reflect.Field handling 2601 // 2602 // 2603 2604 // Returns an array of "root" fields. These Field objects must NOT 2605 // be propagated to the outside world, but must instead be copied 2606 // via ReflectionFactory.copyField. 2607 private Field[] privateGetDeclaredFields(boolean publicOnly) { 2608 checkInitted(); 2609 Field[] res; 2610 ReflectionData<T> rd = reflectionData(); 2611 if (rd != null) { 2612 res = publicOnly ? rd.declaredPublicFields : rd.declaredFields; 2613 if (res != null) return res; 2614 } 2615 // No cached value available; request value from VM 2616 res = Reflection.filterFields(this, getDeclaredFields0(publicOnly)); 2617 if (rd != null) { 2618 if (publicOnly) { 2619 rd.declaredPublicFields = res; 2620 } else { 2621 rd.declaredFields = res; 2622 } 2623 } 2624 return res; 2625 } 2626 2627 // Returns an array of "root" fields. These Field objects must NOT 2628 // be propagated to the outside world, but must instead be copied 2629 // via ReflectionFactory.copyField. 2630 private Field[] privateGetPublicFields(Set<Class<?>> traversedInterfaces) { 2631 checkInitted(); 2632 Field[] res; 2633 ReflectionData<T> rd = reflectionData(); 2634 if (rd != null) { 2635 res = rd.publicFields; 2636 if (res != null) return res; 2637 } 2638 2639 // No cached value available; compute value recursively. 2640 // Traverse in correct order for getField(). 2641 List<Field> fields = new ArrayList<>(); 2642 if (traversedInterfaces == null) { 2643 traversedInterfaces = new HashSet<>(); 2644 } 2645 2646 // Local fields 2647 Field[] tmp = privateGetDeclaredFields(true); 2648 addAll(fields, tmp); 2649 2650 // Direct superinterfaces, recursively 2651 for (Class<?> c : getInterfaces()) { 2652 if (!traversedInterfaces.contains(c)) { 2653 traversedInterfaces.add(c); 2654 addAll(fields, c.privateGetPublicFields(traversedInterfaces)); 2655 } 2656 } 2657 2658 // Direct superclass, recursively 2659 if (!isInterface()) { 2660 Class<?> c = getSuperclass(); 2661 if (c != null) { 2662 addAll(fields, c.privateGetPublicFields(traversedInterfaces)); 2663 } 2664 } 2665 2666 res = new Field[fields.size()]; 2667 fields.toArray(res); 2668 if (rd != null) { 2669 rd.publicFields = res; 2670 } 2671 return res; 2672 } 2673 2674 private static void addAll(Collection<Field> c, Field[] o) { 2675 for (Field f : o) { 2676 c.add(f); 2677 } 2678 } 2679 2680 2681 // 2682 // 2683 // java.lang.reflect.Constructor handling 2684 // 2685 // 2686 2687 // Returns an array of "root" constructors. These Constructor 2688 // objects must NOT be propagated to the outside world, but must 2689 // instead be copied via ReflectionFactory.copyConstructor. 2690 private Constructor<T>[] privateGetDeclaredConstructors(boolean publicOnly) { 2691 checkInitted(); 2692 Constructor<T>[] res; 2693 ReflectionData<T> rd = reflectionData(); 2694 if (rd != null) { 2695 res = publicOnly ? rd.publicConstructors : rd.declaredConstructors; 2696 if (res != null) return res; 2697 } 2698 // No cached value available; request value from VM 2699 if (isInterface()) { 2700 @SuppressWarnings("unchecked") 2701 Constructor<T>[] temporaryRes = (Constructor<T>[]) new Constructor<?>[0]; 2702 res = temporaryRes; 2703 } else { 2704 res = getDeclaredConstructors0(publicOnly); 2705 } 2706 if (rd != null) { 2707 if (publicOnly) { 2708 rd.publicConstructors = res; 2709 } else { 2710 rd.declaredConstructors = res; 2711 } 2712 } 2713 return res; 2714 } 2715 2716 // 2717 // 2718 // java.lang.reflect.Method handling 2719 // 2720 // 2721 2722 // Returns an array of "root" methods. These Method objects must NOT 2723 // be propagated to the outside world, but must instead be copied 2724 // via ReflectionFactory.copyMethod. 2725 private Method[] privateGetDeclaredMethods(boolean publicOnly) { 2726 checkInitted(); 2727 Method[] res; 2728 ReflectionData<T> rd = reflectionData(); 2729 if (rd != null) { 2730 res = publicOnly ? rd.declaredPublicMethods : rd.declaredMethods; 2731 if (res != null) return res; 2732 } 2733 // No cached value available; request value from VM 2734 res = Reflection.filterMethods(this, getDeclaredMethods0(publicOnly)); 2735 if (rd != null) { 2736 if (publicOnly) { 2737 rd.declaredPublicMethods = res; 2738 } else { 2739 rd.declaredMethods = res; 2740 } 2741 } 2742 return res; 2743 } 2744 2745 static class MethodArray { 2746 // Don't add or remove methods except by add() or remove() calls. 2747 private Method[] methods; 2748 private int length; 2749 private int defaults; 2750 2751 MethodArray() { 2752 this(20); 2753 } 2754 2755 MethodArray(int initialSize) { 2756 if (initialSize < 2) 2757 throw new IllegalArgumentException("Size should be 2 or more"); 2758 2759 methods = new Method[initialSize]; 2760 length = 0; 2761 defaults = 0; 2762 } 2763 2764 boolean hasDefaults() { 2765 return defaults != 0; 2766 } 2767 2768 void add(Method m) { 2769 if (length == methods.length) { 2770 methods = Arrays.copyOf(methods, 2 * methods.length); 2771 } 2772 methods[length++] = m; 2773 2774 if (m != null && m.isDefault()) 2775 defaults++; 2776 } 2777 2778 void addAll(Method[] ma) { 2779 for (Method m : ma) { 2780 add(m); 2781 } 2782 } 2783 2784 void addAll(MethodArray ma) { 2785 for (int i = 0; i < ma.length(); i++) { 2786 add(ma.get(i)); 2787 } 2788 } 2789 2790 void addIfNotPresent(Method newMethod) { 2791 for (int i = 0; i < length; i++) { 2792 Method m = methods[i]; 2793 if (m == newMethod || (m != null && m.equals(newMethod))) { 2794 return; 2795 } 2796 } 2797 add(newMethod); 2798 } 2799 2800 void addAllIfNotPresent(MethodArray newMethods) { 2801 for (int i = 0; i < newMethods.length(); i++) { 2802 Method m = newMethods.get(i); 2803 if (m != null) { 2804 addIfNotPresent(m); 2805 } 2806 } 2807 } 2808 2809 /* Add Methods declared in an interface to this MethodArray. 2810 * Static methods declared in interfaces are not inherited. 2811 */ 2812 void addInterfaceMethods(Method[] methods) { 2813 for (Method candidate : methods) { 2814 if (!Modifier.isStatic(candidate.getModifiers())) { 2815 add(candidate); 2816 } 2817 } 2818 } 2819 2820 int length() { 2821 return length; 2822 } 2823 2824 Method get(int i) { 2825 return methods[i]; 2826 } 2827 2828 Method getFirst() { 2829 for (Method m : methods) 2830 if (m != null) 2831 return m; 2832 return null; 2833 } 2834 2835 void removeByNameAndDescriptor(Method toRemove) { 2836 for (int i = 0; i < length; i++) { 2837 Method m = methods[i]; 2838 if (m != null && matchesNameAndDescriptor(m, toRemove)) { 2839 remove(i); 2840 } 2841 } 2842 } 2843 2844 private void remove(int i) { 2845 if (methods[i] != null && methods[i].isDefault()) 2846 defaults--; 2847 methods[i] = null; 2848 } 2849 2850 private boolean matchesNameAndDescriptor(Method m1, Method m2) { 2851 return m1.getReturnType() == m2.getReturnType() && 2852 m1.getName() == m2.getName() && // name is guaranteed to be interned 2853 arrayContentsEq(m1.getParameterTypes(), 2854 m2.getParameterTypes()); 2855 } 2856 2857 void compactAndTrim() { 2858 int newPos = 0; 2859 // Get rid of null slots 2860 for (int pos = 0; pos < length; pos++) { 2861 Method m = methods[pos]; 2862 if (m != null) { 2863 if (pos != newPos) { 2864 methods[newPos] = m; 2865 } 2866 newPos++; 2867 } 2868 } 2869 if (newPos != methods.length) { 2870 methods = Arrays.copyOf(methods, newPos); 2871 } 2872 } 2873 2874 /* Removes all Methods from this MethodArray that have a more specific 2875 * default Method in this MethodArray. 2876 * 2877 * Users of MethodArray are responsible for pruning Methods that have 2878 * a more specific <em>concrete</em> Method. 2879 */ 2880 void removeLessSpecifics() { 2881 if (!hasDefaults()) 2882 return; 2883 2884 for (int i = 0; i < length; i++) { 2885 Method m = get(i); 2886 if (m == null || !m.isDefault()) 2887 continue; 2888 2889 for (int j = 0; j < length; j++) { 2890 if (i == j) 2891 continue; 2892 2893 Method candidate = get(j); 2894 if (candidate == null) 2895 continue; 2896 2897 if (!matchesNameAndDescriptor(m, candidate)) 2898 continue; 2899 2900 if (hasMoreSpecificClass(m, candidate)) 2901 remove(j); 2902 } 2903 } 2904 } 2905 2906 Method[] getArray() { 2907 return methods; 2908 } 2909 2910 // Returns true if m1 is more specific than m2 2911 static boolean hasMoreSpecificClass(Method m1, Method m2) { 2912 Class<?> m1Class = m1.getDeclaringClass(); 2913 Class<?> m2Class = m2.getDeclaringClass(); 2914 return m1Class != m2Class && m2Class.isAssignableFrom(m1Class); 2915 } 2916 } 2917 2918 2919 // Returns an array of "root" methods. These Method objects must NOT 2920 // be propagated to the outside world, but must instead be copied 2921 // via ReflectionFactory.copyMethod. 2922 private Method[] privateGetPublicMethods() { 2923 checkInitted(); 2924 Method[] res; 2925 ReflectionData<T> rd = reflectionData(); 2926 if (rd != null) { 2927 res = rd.publicMethods; 2928 if (res != null) return res; 2929 } 2930 2931 // No cached value available; compute value recursively. 2932 // Start by fetching public declared methods 2933 MethodArray methods = new MethodArray(); 2934 { 2935 Method[] tmp = privateGetDeclaredMethods(true); 2936 methods.addAll(tmp); 2937 } 2938 // Now recur over superclass and direct superinterfaces. 2939 // Go over superinterfaces first so we can more easily filter 2940 // out concrete implementations inherited from superclasses at 2941 // the end. 2942 MethodArray inheritedMethods = new MethodArray(); 2943 for (Class<?> i : getInterfaces()) { 2944 inheritedMethods.addInterfaceMethods(i.privateGetPublicMethods()); 2945 } 2946 if (!isInterface()) { 2947 Class<?> c = getSuperclass(); 2948 if (c != null) { 2949 MethodArray supers = new MethodArray(); 2950 supers.addAll(c.privateGetPublicMethods()); 2951 // Filter out concrete implementations of any 2952 // interface methods 2953 for (int i = 0; i < supers.length(); i++) { 2954 Method m = supers.get(i); 2955 if (m != null && 2956 !Modifier.isAbstract(m.getModifiers()) && 2957 !m.isDefault()) { 2958 inheritedMethods.removeByNameAndDescriptor(m); 2959 } 2960 } 2961 // Insert superclass's inherited methods before 2962 // superinterfaces' to satisfy getMethod's search 2963 // order 2964 supers.addAll(inheritedMethods); 2965 inheritedMethods = supers; 2966 } 2967 } 2968 // Filter out all local methods from inherited ones 2969 for (int i = 0; i < methods.length(); i++) { 2970 Method m = methods.get(i); 2971 inheritedMethods.removeByNameAndDescriptor(m); 2972 } 2973 methods.addAllIfNotPresent(inheritedMethods); 2974 methods.removeLessSpecifics(); 2975 methods.compactAndTrim(); 2976 res = methods.getArray(); 2977 if (rd != null) { 2978 rd.publicMethods = res; 2979 } 2980 return res; 2981 } 2982 2983 2984 // 2985 // Helpers for fetchers of one field, method, or constructor 2986 // 2987 2988 private static Field searchFields(Field[] fields, String name) { 2989 String internedName = name.intern(); 2990 for (Field field : fields) { 2991 if (field.getName() == internedName) { 2992 return getReflectionFactory().copyField(field); 2993 } 2994 } 2995 return null; 2996 } 2997 2998 private Field getField0(String name) throws NoSuchFieldException { 2999 // Note: the intent is that the search algorithm this routine 3000 // uses be equivalent to the ordering imposed by 3001 // privateGetPublicFields(). It fetches only the declared 3002 // public fields for each class, however, to reduce the number 3003 // of Field objects which have to be created for the common 3004 // case where the field being requested is declared in the 3005 // class which is being queried. 3006 Field res; 3007 // Search declared public fields 3008 if ((res = searchFields(privateGetDeclaredFields(true), name)) != null) { 3009 return res; 3010 } 3011 // Direct superinterfaces, recursively 3012 Class<?>[] interfaces = getInterfaces(); 3013 for (Class<?> c : interfaces) { 3014 if ((res = c.getField0(name)) != null) { 3015 return res; 3016 } 3017 } 3018 // Direct superclass, recursively 3019 if (!isInterface()) { 3020 Class<?> c = getSuperclass(); 3021 if (c != null) { 3022 if ((res = c.getField0(name)) != null) { 3023 return res; 3024 } 3025 } 3026 } 3027 return null; 3028 } 3029 3030 private static Method searchMethods(Method[] methods, 3031 String name, 3032 Class<?>[] parameterTypes) 3033 { 3034 Method res = null; 3035 String internedName = name.intern(); 3036 for (Method m : methods) { 3037 if (m.getName() == internedName 3038 && arrayContentsEq(parameterTypes, m.getParameterTypes()) 3039 && (res == null 3040 || res.getReturnType().isAssignableFrom(m.getReturnType()))) 3041 res = m; 3042 } 3043 3044 return (res == null ? res : getReflectionFactory().copyMethod(res)); 3045 } 3046 3047 private Method getMethod0(String name, Class<?>[] parameterTypes, boolean includeStaticMethods) { 3048 MethodArray interfaceCandidates = new MethodArray(2); 3049 Method res = privateGetMethodRecursive(name, parameterTypes, includeStaticMethods, interfaceCandidates); 3050 if (res != null) 3051 return res; 3052 3053 // Not found on class or superclass directly 3054 interfaceCandidates.removeLessSpecifics(); 3055 return interfaceCandidates.getFirst(); // may be null 3056 } 3057 3058 private Method privateGetMethodRecursive(String name, 3059 Class<?>[] parameterTypes, 3060 boolean includeStaticMethods, 3061 MethodArray allInterfaceCandidates) { 3062 // Note: the intent is that the search algorithm this routine 3063 // uses be equivalent to the ordering imposed by 3064 // privateGetPublicMethods(). It fetches only the declared 3065 // public methods for each class, however, to reduce the 3066 // number of Method objects which have to be created for the 3067 // common case where the method being requested is declared in 3068 // the class which is being queried. 3069 // 3070 // Due to default methods, unless a method is found on a superclass, 3071 // methods declared in any superinterface needs to be considered. 3072 // Collect all candidates declared in superinterfaces in {@code 3073 // allInterfaceCandidates} and select the most specific if no match on 3074 // a superclass is found. 3075 3076 // Must _not_ return root methods 3077 Method res; 3078 // Search declared public methods 3079 if ((res = searchMethods(privateGetDeclaredMethods(true), 3080 name, 3081 parameterTypes)) != null) { 3082 if (includeStaticMethods || !Modifier.isStatic(res.getModifiers())) 3083 return res; 3084 } 3085 // Search superclass's methods 3086 if (!isInterface()) { 3087 Class<? super T> c = getSuperclass(); 3088 if (c != null) { 3089 if ((res = c.getMethod0(name, parameterTypes, true)) != null) { 3090 return res; 3091 } 3092 } 3093 } 3094 // Search superinterfaces' methods 3095 Class<?>[] interfaces = getInterfaces(); 3096 for (Class<?> c : interfaces) 3097 if ((res = c.getMethod0(name, parameterTypes, false)) != null) 3098 allInterfaceCandidates.add(res); 3099 // Not found 3100 return null; 3101 } 3102 3103 private Constructor<T> getConstructor0(Class<?>[] parameterTypes, 3104 int which) throws NoSuchMethodException 3105 { 3106 Constructor<T>[] constructors = privateGetDeclaredConstructors((which == Member.PUBLIC)); 3107 for (Constructor<T> constructor : constructors) { 3108 if (arrayContentsEq(parameterTypes, 3109 constructor.getParameterTypes())) { 3110 return getReflectionFactory().copyConstructor(constructor); 3111 } 3112 } 3113 throw new NoSuchMethodException(getName() + ".<init>" + argumentTypesToString(parameterTypes)); 3114 } 3115 3116 // 3117 // Other helpers and base implementation 3118 // 3119 3120 private static boolean arrayContentsEq(Object[] a1, Object[] a2) { 3121 if (a1 == null) { 3122 return a2 == null || a2.length == 0; 3123 } 3124 3125 if (a2 == null) { 3126 return a1.length == 0; 3127 } 3128 3129 if (a1.length != a2.length) { 3130 return false; 3131 } 3132 3133 for (int i = 0; i < a1.length; i++) { 3134 if (a1[i] != a2[i]) { 3135 return false; 3136 } 3137 } 3138 3139 return true; 3140 } 3141 3142 private static Field[] copyFields(Field[] arg) { 3143 Field[] out = new Field[arg.length]; 3144 ReflectionFactory fact = getReflectionFactory(); 3145 for (int i = 0; i < arg.length; i++) { 3146 out[i] = fact.copyField(arg[i]); 3147 } 3148 return out; 3149 } 3150 3151 private static Method[] copyMethods(Method[] arg) { 3152 Method[] out = new Method[arg.length]; 3153 ReflectionFactory fact = getReflectionFactory(); 3154 for (int i = 0; i < arg.length; i++) { 3155 out[i] = fact.copyMethod(arg[i]); 3156 } 3157 return out; 3158 } 3159 3160 private static <U> Constructor<U>[] copyConstructors(Constructor<U>[] arg) { 3161 Constructor<U>[] out = arg.clone(); 3162 ReflectionFactory fact = getReflectionFactory(); 3163 for (int i = 0; i < out.length; i++) { 3164 out[i] = fact.copyConstructor(out[i]); 3165 } 3166 return out; 3167 } 3168 3169 private native Field[] getDeclaredFields0(boolean publicOnly); 3170 private native Method[] getDeclaredMethods0(boolean publicOnly); 3171 private native Constructor<T>[] getDeclaredConstructors0(boolean publicOnly); 3172 private native Class<?>[] getDeclaredClasses0(); 3173 3174 private static String argumentTypesToString(Class<?>[] argTypes) { 3175 StringJoiner sj = new StringJoiner(", ", "(", ")"); 3176 if (argTypes != null) { 3177 for (int i = 0; i < argTypes.length; i++) { 3178 Class<?> c = argTypes[i]; 3179 sj.add((c == null) ? "null" : c.getName()); 3180 } 3181 } 3182 return sj.toString(); 3183 } 3184 3185 /** use serialVersionUID from JDK 1.1 for interoperability */ 3186 private static final long serialVersionUID = 3206093459760846163L; 3187 3188 3189 /** 3190 * Class Class is special cased within the Serialization Stream Protocol. 3191 * 3192 * A Class instance is written initially into an ObjectOutputStream in the 3193 * following format: 3194 * <pre> 3195 * {@code TC_CLASS} ClassDescriptor 3196 * A ClassDescriptor is a special cased serialization of 3197 * a {@code java.io.ObjectStreamClass} instance. 3198 * </pre> 3199 * A new handle is generated for the initial time the class descriptor 3200 * is written into the stream. Future references to the class descriptor 3201 * are written as references to the initial class descriptor instance. 3202 * 3203 * @see java.io.ObjectStreamClass 3204 */ 3205 private static final ObjectStreamField[] serialPersistentFields = 3206 new ObjectStreamField[0]; 3207 3208 3209 /** 3210 * Returns the assertion status that would be assigned to this 3211 * class if it were to be initialized at the time this method is invoked. 3212 * If this class has had its assertion status set, the most recent 3213 * setting will be returned; otherwise, if any package default assertion 3214 * status pertains to this class, the most recent setting for the most 3215 * specific pertinent package default assertion status is returned; 3216 * otherwise, if this class is not a system class (i.e., it has a 3217 * class loader) its class loader's default assertion status is returned; 3218 * otherwise, the system class default assertion status is returned. 3219 * <p> 3220 * Few programmers will have any need for this method; it is provided 3221 * for the benefit of the JRE itself. (It allows a class to determine at 3222 * the time that it is initialized whether assertions should be enabled.) 3223 * Note that this method is not guaranteed to return the actual 3224 * assertion status that was (or will be) associated with the specified 3225 * class when it was (or will be) initialized. 3226 * 3227 * @return the desired assertion status of the specified class. 3228 * @see java.lang.ClassLoader#setClassAssertionStatus 3229 * @see java.lang.ClassLoader#setPackageAssertionStatus 3230 * @see java.lang.ClassLoader#setDefaultAssertionStatus 3231 * @since 1.4 3232 */ 3233 public boolean desiredAssertionStatus() { 3234 ClassLoader loader = getClassLoader(); 3235 // If the loader is null this is a system class, so ask the VM 3236 if (loader == null) 3237 return desiredAssertionStatus0(this); 3238 3239 // If the classloader has been initialized with the assertion 3240 // directives, ask it. Otherwise, ask the VM. 3241 synchronized(loader.assertionLock) { 3242 if (loader.classAssertionStatus != null) { 3243 return loader.desiredAssertionStatus(getName()); 3244 } 3245 } 3246 return desiredAssertionStatus0(this); 3247 } 3248 3249 // Retrieves the desired assertion status of this class from the VM 3250 private static native boolean desiredAssertionStatus0(Class<?> clazz); 3251 3252 /** 3253 * Returns true if and only if this class was declared as an enum in the 3254 * source code. 3255 * 3256 * @return true if and only if this class was declared as an enum in the 3257 * source code 3258 * @since 1.5 3259 */ 3260 public boolean isEnum() { 3261 // An enum must both directly extend java.lang.Enum and have 3262 // the ENUM bit set; classes for specialized enum constants 3263 // don't do the former. 3264 return (this.getModifiers() & ENUM) != 0 && 3265 this.getSuperclass() == java.lang.Enum.class; 3266 } 3267 3268 // Fetches the factory for reflective objects 3269 private static ReflectionFactory getReflectionFactory() { 3270 if (reflectionFactory == null) { 3271 reflectionFactory = 3272 java.security.AccessController.doPrivileged 3273 (new sun.reflect.ReflectionFactory.GetReflectionFactoryAction()); 3274 } 3275 return reflectionFactory; 3276 } 3277 private static ReflectionFactory reflectionFactory; 3278 3279 // To be able to query system properties as soon as they're available 3280 private static boolean initted = false; 3281 private static void checkInitted() { 3282 if (initted) return; 3283 AccessController.doPrivileged(new PrivilegedAction<>() { 3284 public Void run() { 3285 // Tests to ensure the system properties table is fully 3286 // initialized. This is needed because reflection code is 3287 // called very early in the initialization process (before 3288 // command-line arguments have been parsed and therefore 3289 // these user-settable properties installed.) We assume that 3290 // if System.out is non-null then the System class has been 3291 // fully initialized and that the bulk of the startup code 3292 // has been run. 3293 3294 if (System.out == null) { 3295 // java.lang.System not yet fully initialized 3296 return null; 3297 } 3298 3299 // Doesn't use Boolean.getBoolean to avoid class init. 3300 String val = 3301 System.getProperty("sun.reflect.noCaches"); 3302 if (val != null && val.equals("true")) { 3303 useCaches = false; 3304 } 3305 3306 initted = true; 3307 return null; 3308 } 3309 }); 3310 } 3311 3312 /** 3313 * Returns the elements of this enum class or null if this 3314 * Class object does not represent an enum type. 3315 * 3316 * @return an array containing the values comprising the enum class 3317 * represented by this Class object in the order they're 3318 * declared, or null if this Class object does not 3319 * represent an enum type 3320 * @since 1.5 3321 */ 3322 public T[] getEnumConstants() { 3323 T[] values = getEnumConstantsShared(); 3324 return (values != null) ? values.clone() : null; 3325 } 3326 3327 /** 3328 * Returns the elements of this enum class or null if this 3329 * Class object does not represent an enum type; 3330 * identical to getEnumConstants except that the result is 3331 * uncloned, cached, and shared by all callers. 3332 */ 3333 T[] getEnumConstantsShared() { 3334 if (enumConstants == null) { 3335 if (!isEnum()) return null; 3336 try { 3337 final Method values = getMethod("values"); 3338 java.security.AccessController.doPrivileged( 3339 new java.security.PrivilegedAction<>() { 3340 public Void run() { 3341 values.setAccessible(true); 3342 return null; 3343 } 3344 }); 3345 @SuppressWarnings("unchecked") 3346 T[] temporaryConstants = (T[])values.invoke(null); 3347 enumConstants = temporaryConstants; 3348 } 3349 // These can happen when users concoct enum-like classes 3350 // that don't comply with the enum spec. 3351 catch (InvocationTargetException | NoSuchMethodException | 3352 IllegalAccessException ex) { return null; } 3353 } 3354 return enumConstants; 3355 } 3356 private volatile transient T[] enumConstants = null; 3357 3358 /** 3359 * Returns a map from simple name to enum constant. This package-private 3360 * method is used internally by Enum to implement 3361 * {@code public static <T extends Enum<T>> T valueOf(Class<T>, String)} 3362 * efficiently. Note that the map is returned by this method is 3363 * created lazily on first use. Typically it won't ever get created. 3364 */ 3365 Map<String, T> enumConstantDirectory() { 3366 if (enumConstantDirectory == null) { 3367 T[] universe = getEnumConstantsShared(); 3368 if (universe == null) 3369 throw new IllegalArgumentException( 3370 getName() + " is not an enum type"); 3371 Map<String, T> m = new HashMap<>(2 * universe.length); 3372 for (T constant : universe) 3373 m.put(((Enum<?>)constant).name(), constant); 3374 enumConstantDirectory = m; 3375 } 3376 return enumConstantDirectory; 3377 } 3378 private volatile transient Map<String, T> enumConstantDirectory = null; 3379 3380 /** 3381 * Casts an object to the class or interface represented 3382 * by this {@code Class} object. 3383 * 3384 * @param obj the object to be cast 3385 * @return the object after casting, or null if obj is null 3386 * 3387 * @throws ClassCastException if the object is not 3388 * null and is not assignable to the type T. 3389 * 3390 * @since 1.5 3391 */ 3392 @SuppressWarnings("unchecked") 3393 @HotSpotIntrinsicCandidate 3394 public T cast(Object obj) { 3395 if (obj != null && !isInstance(obj)) 3396 throw new ClassCastException(cannotCastMsg(obj)); 3397 return (T) obj; 3398 } 3399 3400 private String cannotCastMsg(Object obj) { 3401 return "Cannot cast " + obj.getClass().getName() + " to " + getName(); 3402 } 3403 3404 /** 3405 * Casts this {@code Class} object to represent a subclass of the class 3406 * represented by the specified class object. Checks that the cast 3407 * is valid, and throws a {@code ClassCastException} if it is not. If 3408 * this method succeeds, it always returns a reference to this class object. 3409 * 3410 * <p>This method is useful when a client needs to "narrow" the type of 3411 * a {@code Class} object to pass it to an API that restricts the 3412 * {@code Class} objects that it is willing to accept. A cast would 3413 * generate a compile-time warning, as the correctness of the cast 3414 * could not be checked at runtime (because generic types are implemented 3415 * by erasure). 3416 * 3417 * @param <U> the type to cast this class object to 3418 * @param clazz the class of the type to cast this class object to 3419 * @return this {@code Class} object, cast to represent a subclass of 3420 * the specified class object. 3421 * @throws ClassCastException if this {@code Class} object does not 3422 * represent a subclass of the specified class (here "subclass" includes 3423 * the class itself). 3424 * @since 1.5 3425 */ 3426 @SuppressWarnings("unchecked") 3427 public <U> Class<? extends U> asSubclass(Class<U> clazz) { 3428 if (clazz.isAssignableFrom(this)) 3429 return (Class<? extends U>) this; 3430 else 3431 throw new ClassCastException(this.toString()); 3432 } 3433 3434 /** 3435 * @throws NullPointerException {@inheritDoc} 3436 * @since 1.5 3437 */ 3438 @SuppressWarnings("unchecked") 3439 public <A extends Annotation> A getAnnotation(Class<A> annotationClass) { 3440 Objects.requireNonNull(annotationClass); 3441 3442 return (A) annotationData().annotations.get(annotationClass); 3443 } 3444 3445 /** 3446 * {@inheritDoc} 3447 * @throws NullPointerException {@inheritDoc} 3448 * @since 1.5 3449 */ 3450 @Override 3451 public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) { 3452 return GenericDeclaration.super.isAnnotationPresent(annotationClass); 3453 } 3454 3455 /** 3456 * @throws NullPointerException {@inheritDoc} 3457 * @since 1.8 3458 */ 3459 @Override 3460 public <A extends Annotation> A[] getAnnotationsByType(Class<A> annotationClass) { 3461 Objects.requireNonNull(annotationClass); 3462 3463 AnnotationData annotationData = annotationData(); 3464 return AnnotationSupport.getAssociatedAnnotations(annotationData.declaredAnnotations, 3465 this, 3466 annotationClass); 3467 } 3468 3469 /** 3470 * @since 1.5 3471 */ 3472 public Annotation[] getAnnotations() { 3473 return AnnotationParser.toArray(annotationData().annotations); 3474 } 3475 3476 /** 3477 * @throws NullPointerException {@inheritDoc} 3478 * @since 1.8 3479 */ 3480 @Override 3481 @SuppressWarnings("unchecked") 3482 public <A extends Annotation> A getDeclaredAnnotation(Class<A> annotationClass) { 3483 Objects.requireNonNull(annotationClass); 3484 3485 return (A) annotationData().declaredAnnotations.get(annotationClass); 3486 } 3487 3488 /** 3489 * @throws NullPointerException {@inheritDoc} 3490 * @since 1.8 3491 */ 3492 @Override 3493 public <A extends Annotation> A[] getDeclaredAnnotationsByType(Class<A> annotationClass) { 3494 Objects.requireNonNull(annotationClass); 3495 3496 return AnnotationSupport.getDirectlyAndIndirectlyPresent(annotationData().declaredAnnotations, 3497 annotationClass); 3498 } 3499 3500 /** 3501 * @since 1.5 3502 */ 3503 public Annotation[] getDeclaredAnnotations() { 3504 return AnnotationParser.toArray(annotationData().declaredAnnotations); 3505 } 3506 3507 // annotation data that might get invalidated when JVM TI RedefineClasses() is called 3508 private static class AnnotationData { 3509 final Map<Class<? extends Annotation>, Annotation> annotations; 3510 final Map<Class<? extends Annotation>, Annotation> declaredAnnotations; 3511 3512 // Value of classRedefinedCount when we created this AnnotationData instance 3513 final int redefinedCount; 3514 3515 AnnotationData(Map<Class<? extends Annotation>, Annotation> annotations, 3516 Map<Class<? extends Annotation>, Annotation> declaredAnnotations, 3517 int redefinedCount) { 3518 this.annotations = annotations; 3519 this.declaredAnnotations = declaredAnnotations; 3520 this.redefinedCount = redefinedCount; 3521 } 3522 } 3523 3524 // Annotations cache 3525 @SuppressWarnings("UnusedDeclaration") 3526 private volatile transient AnnotationData annotationData; 3527 3528 private AnnotationData annotationData() { 3529 while (true) { // retry loop 3530 AnnotationData annotationData = this.annotationData; 3531 int classRedefinedCount = this.classRedefinedCount; 3532 if (annotationData != null && 3533 annotationData.redefinedCount == classRedefinedCount) { 3534 return annotationData; 3535 } 3536 // null or stale annotationData -> optimistically create new instance 3537 AnnotationData newAnnotationData = createAnnotationData(classRedefinedCount); 3538 // try to install it 3539 if (Atomic.casAnnotationData(this, annotationData, newAnnotationData)) { 3540 // successfully installed new AnnotationData 3541 return newAnnotationData; 3542 } 3543 } 3544 } 3545 3546 private AnnotationData createAnnotationData(int classRedefinedCount) { 3547 Map<Class<? extends Annotation>, Annotation> declaredAnnotations = 3548 AnnotationParser.parseAnnotations(getRawAnnotations(), getConstantPool(), this); 3549 Class<?> superClass = getSuperclass(); 3550 Map<Class<? extends Annotation>, Annotation> annotations = null; 3551 if (superClass != null) { 3552 Map<Class<? extends Annotation>, Annotation> superAnnotations = 3553 superClass.annotationData().annotations; 3554 for (Map.Entry<Class<? extends Annotation>, Annotation> e : superAnnotations.entrySet()) { 3555 Class<? extends Annotation> annotationClass = e.getKey(); 3556 if (AnnotationType.getInstance(annotationClass).isInherited()) { 3557 if (annotations == null) { // lazy construction 3558 annotations = new LinkedHashMap<>((Math.max( 3559 declaredAnnotations.size(), 3560 Math.min(12, declaredAnnotations.size() + superAnnotations.size()) 3561 ) * 4 + 2) / 3 3562 ); 3563 } 3564 annotations.put(annotationClass, e.getValue()); 3565 } 3566 } 3567 } 3568 if (annotations == null) { 3569 // no inherited annotations -> share the Map with declaredAnnotations 3570 annotations = declaredAnnotations; 3571 } else { 3572 // at least one inherited annotation -> declared may override inherited 3573 annotations.putAll(declaredAnnotations); 3574 } 3575 return new AnnotationData(annotations, declaredAnnotations, classRedefinedCount); 3576 } 3577 3578 // Annotation types cache their internal (AnnotationType) form 3579 3580 @SuppressWarnings("UnusedDeclaration") 3581 private volatile transient AnnotationType annotationType; 3582 3583 boolean casAnnotationType(AnnotationType oldType, AnnotationType newType) { 3584 return Atomic.casAnnotationType(this, oldType, newType); 3585 } 3586 3587 AnnotationType getAnnotationType() { 3588 return annotationType; 3589 } 3590 3591 Map<Class<? extends Annotation>, Annotation> getDeclaredAnnotationMap() { 3592 return annotationData().declaredAnnotations; 3593 } 3594 3595 /* Backing store of user-defined values pertaining to this class. 3596 * Maintained by the ClassValue class. 3597 */ 3598 transient ClassValue.ClassValueMap classValueMap; 3599 3600 /** 3601 * Returns an {@code AnnotatedType} object that represents the use of a 3602 * type to specify the superclass of the entity represented by this {@code 3603 * Class} object. (The <em>use</em> of type Foo to specify the superclass 3604 * in '... extends Foo' is distinct from the <em>declaration</em> of type 3605 * Foo.) 3606 * 3607 * <p> If this {@code Class} object represents a type whose declaration 3608 * does not explicitly indicate an annotated superclass, then the return 3609 * value is an {@code AnnotatedType} object representing an element with no 3610 * annotations. 3611 * 3612 * <p> If this {@code Class} represents either the {@code Object} class, an 3613 * interface type, an array type, a primitive type, or void, the return 3614 * value is {@code null}. 3615 * 3616 * @return an object representing the superclass 3617 * @since 1.8 3618 */ 3619 public AnnotatedType getAnnotatedSuperclass() { 3620 if (this == Object.class || 3621 isInterface() || 3622 isArray() || 3623 isPrimitive() || 3624 this == Void.TYPE) { 3625 return null; 3626 } 3627 3628 return TypeAnnotationParser.buildAnnotatedSuperclass(getRawTypeAnnotations(), getConstantPool(), this); 3629 } 3630 3631 /** 3632 * Returns an array of {@code AnnotatedType} objects that represent the use 3633 * of types to specify superinterfaces of the entity represented by this 3634 * {@code Class} object. (The <em>use</em> of type Foo to specify a 3635 * superinterface in '... implements Foo' is distinct from the 3636 * <em>declaration</em> of type Foo.) 3637 * 3638 * <p> If this {@code Class} object represents a class, the return value is 3639 * an array containing objects representing the uses of interface types to 3640 * specify interfaces implemented by the class. The order of the objects in 3641 * the array corresponds to the order of the interface types used in the 3642 * 'implements' clause of the declaration of this {@code Class} object. 3643 * 3644 * <p> If this {@code Class} object represents an interface, the return 3645 * value is an array containing objects representing the uses of interface 3646 * types to specify interfaces directly extended by the interface. The 3647 * order of the objects in the array corresponds to the order of the 3648 * interface types used in the 'extends' clause of the declaration of this 3649 * {@code Class} object. 3650 * 3651 * <p> If this {@code Class} object represents a class or interface whose 3652 * declaration does not explicitly indicate any annotated superinterfaces, 3653 * the return value is an array of length 0. 3654 * 3655 * <p> If this {@code Class} object represents either the {@code Object} 3656 * class, an array type, a primitive type, or void, the return value is an 3657 * array of length 0. 3658 * 3659 * @return an array representing the superinterfaces 3660 * @since 1.8 3661 */ 3662 public AnnotatedType[] getAnnotatedInterfaces() { 3663 return TypeAnnotationParser.buildAnnotatedInterfaces(getRawTypeAnnotations(), getConstantPool(), this); 3664 } 3665 }