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