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