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