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