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