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