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