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