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