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