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