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