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