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