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