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