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