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