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