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