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