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