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 class="borderless"> 728 * <caption style="display:none">Element types and encodings</caption> 729 * <thead> 730 * <tr><th style="padding-right:3em;"> Element Type <th> Encoding 731 * </thead> 732 * <tbody> 733 * <tr><td> boolean <td style="text-align:center"> Z 734 * <tr><td> byte <td style="text-align:center"> B 735 * <tr><td> char <td style="text-align:center"> C 736 * <tr><td> class or interface 737 * <td style="text-align:center"> L<i>classname</i>; 738 * <tr><td> double <td style="text-align:center"> D 739 * <tr><td> float <td style="text-align:center"> F 740 * <tr><td> int <td style="text-align:center"> I 741 * <tr><td> long <td style="text-align:center"> J 742 * <tr><td> short <td style="text-align:center"> S 743 * </tbody> 744 * </table></blockquote> 745 * 746 * <p> The class or interface name <i>classname</i> is the binary name of 747 * the class specified above. 748 * 749 * <p> Examples: 750 * <blockquote><pre> 751 * String.class.getName() 752 * returns "java.lang.String" 753 * byte.class.getName() 754 * returns "byte" 755 * (new Object[3]).getClass().getName() 756 * returns "[Ljava.lang.Object;" 757 * (new int[3][4][5][6][7][8][9]).getClass().getName() 758 * returns "[[[[[[[I" 759 * </pre></blockquote> 760 * 761 * @return the name of the class or interface 762 * represented by this object. 763 */ 764 public String getName() { 765 String name = this.name; 766 if (name == null) 767 this.name = name = getName0(); 768 return name; 769 } 770 771 // cache the name to reduce the number of calls into the VM 772 private transient String name; 773 private native String getName0(); 774 775 /** 776 * Returns the class loader for the class. Some implementations may use 777 * null to represent the bootstrap class loader. This method will return 778 * null in such implementations if this class was loaded by the bootstrap 779 * class loader. 780 * 781 * <p>If this object 782 * represents a primitive type or void, null is returned. 783 * 784 * @return the class loader that loaded the class or interface 785 * represented by this object. 786 * @throws SecurityException 787 * if a security manager is present, and the caller's class loader 788 * is not {@code null} and is not the same as or an ancestor of the 789 * class loader for the class whose class loader is requested, 790 * and the caller does not have the 791 * {@link RuntimePermission}{@code ("getClassLoader")} 792 * @see java.lang.ClassLoader 793 * @see SecurityManager#checkPermission 794 * @see java.lang.RuntimePermission 795 */ 796 @CallerSensitive 797 @ForceInline // to ensure Reflection.getCallerClass optimization 798 public ClassLoader getClassLoader() { 799 ClassLoader cl = getClassLoader0(); 800 if (cl == null) 801 return null; 802 SecurityManager sm = System.getSecurityManager(); 803 if (sm != null) { 804 ClassLoader.checkClassLoaderPermission(cl, Reflection.getCallerClass()); 805 } 806 return cl; 807 } 808 809 // Package-private to allow ClassLoader access 810 ClassLoader getClassLoader0() { return classLoader; } 811 812 /** 813 * Returns the module that this class or interface is a member of. 814 * 815 * If this class represents an array type then this method returns the 816 * {@code Module} for the element type. If this class represents a 817 * primitive type or void, then the {@code Module} object for the 818 * {@code java.base} module is returned. 819 * 820 * If this class is in an unnamed module then the {@link 821 * ClassLoader#getUnnamedModule() unnamed} {@code Module} of the class 822 * loader for this class is returned. 823 * 824 * @return the module that this class or interface is a member of 825 * 826 * @since 9 827 * @spec JPMS 828 */ 829 public Module getModule() { 830 return module; 831 } 832 833 // set by VM 834 private transient Module module; 835 836 // Initialized in JVM not by private constructor 837 // This field is filtered from reflection access, i.e. getDeclaredField 838 // will throw NoSuchFieldException 839 private final ClassLoader classLoader; 840 841 /** 842 * Returns an array of {@code TypeVariable} objects that represent the 843 * type variables declared by the generic declaration represented by this 844 * {@code GenericDeclaration} object, in declaration order. Returns an 845 * array of length 0 if the underlying generic declaration declares no type 846 * variables. 847 * 848 * @return an array of {@code TypeVariable} objects that represent 849 * the type variables declared by this generic declaration 850 * @throws java.lang.reflect.GenericSignatureFormatError if the generic 851 * signature of this generic declaration does not conform to 852 * the format specified in 853 * <cite>The Java™ Virtual Machine Specification</cite> 854 * @since 1.5 855 */ 856 @SuppressWarnings("unchecked") 857 public TypeVariable<Class<T>>[] getTypeParameters() { 858 ClassRepository info = getGenericInfo(); 859 if (info != null) 860 return (TypeVariable<Class<T>>[])info.getTypeParameters(); 861 else 862 return (TypeVariable<Class<T>>[])new TypeVariable<?>[0]; 863 } 864 865 866 /** 867 * Returns the {@code Class} representing the direct superclass of the 868 * entity (class, interface, primitive type or void) represented by 869 * this {@code Class}. If this {@code Class} represents either the 870 * {@code Object} class, an interface, a primitive type, or void, then 871 * null is returned. If this object represents an array class then the 872 * {@code Class} object representing the {@code Object} class is 873 * returned. 874 * 875 * @return the direct superclass of the class represented by this object 876 */ 877 @HotSpotIntrinsicCandidate 878 public native Class<? super T> getSuperclass(); 879 880 881 /** 882 * Returns the {@code Type} representing the direct superclass of 883 * the entity (class, interface, primitive type or void) represented by 884 * this {@code Class}. 885 * 886 * <p>If the superclass is a parameterized type, the {@code Type} 887 * object returned must accurately reflect the actual type 888 * parameters used in the source code. The parameterized type 889 * representing the superclass is created if it had not been 890 * created before. See the declaration of {@link 891 * java.lang.reflect.ParameterizedType ParameterizedType} for the 892 * semantics of the creation process for parameterized types. If 893 * this {@code Class} represents either the {@code Object} 894 * class, an interface, a primitive type, or void, then null is 895 * returned. If this object represents an array class then the 896 * {@code Class} object representing the {@code Object} class is 897 * returned. 898 * 899 * @throws java.lang.reflect.GenericSignatureFormatError if the generic 900 * class signature does not conform to the format specified in 901 * <cite>The Java™ Virtual Machine Specification</cite> 902 * @throws TypeNotPresentException if the generic superclass 903 * refers to a non-existent type declaration 904 * @throws java.lang.reflect.MalformedParameterizedTypeException if the 905 * generic superclass refers to a parameterized type that cannot be 906 * instantiated for any reason 907 * @return the direct superclass of the class represented by this object 908 * @since 1.5 909 */ 910 public Type getGenericSuperclass() { 911 ClassRepository info = getGenericInfo(); 912 if (info == null) { 913 return getSuperclass(); 914 } 915 916 // Historical irregularity: 917 // Generic signature marks interfaces with superclass = Object 918 // but this API returns null for interfaces 919 if (isInterface()) { 920 return null; 921 } 922 923 return info.getSuperclass(); 924 } 925 926 /** 927 * Gets the package of this class. 928 * 929 * <p>If this class represents an array type, a primitive type or void, 930 * this method returns {@code null}. 931 * 932 * @return the package of this class. 933 * @revised 9 934 * @spec JPMS 935 */ 936 public Package getPackage() { 937 if (isPrimitive() || isArray()) { 938 return null; 939 } 940 ClassLoader cl = getClassLoader0(); 941 return cl != null ? cl.definePackage(this) 942 : BootLoader.definePackage(this); 943 } 944 945 /** 946 * Returns the fully qualified package name. 947 * 948 * <p> If this class is a top level class, then this method returns the fully 949 * qualified name of the package that the class is a member of, or the 950 * empty string if the class is in an unnamed package. 951 * 952 * <p> If this class is a member class, then this method is equivalent to 953 * invoking {@code getPackageName()} on the {@link #getEnclosingClass 954 * enclosing class}. 955 * 956 * <p> If this class is a {@link #isLocalClass local class} or an {@link 957 * #isAnonymousClass() anonymous class}, then this method is equivalent to 958 * invoking {@code getPackageName()} on the {@link #getDeclaringClass 959 * declaring class} of the {@link #getEnclosingMethod enclosing method} or 960 * {@link #getEnclosingConstructor enclosing constructor}. 961 * 962 * <p> If this class represents an array type then this method returns the 963 * package name of the element type. If this class represents a primitive 964 * type or void then the package name "{@code java.lang}" is returned. 965 * 966 * @return the fully qualified package name 967 * 968 * @since 9 969 * @spec JPMS 970 * @jls 6.7 Fully Qualified Names 971 */ 972 public String getPackageName() { 973 String pn = this.packageName; 974 if (pn == null) { 975 Class<?> c = this; 976 while (c.isArray()) { 977 c = c.getComponentType(); 978 } 979 if (c.isPrimitive()) { 980 pn = "java.lang"; 981 } else { 982 String cn = c.getName(); 983 int dot = cn.lastIndexOf('.'); 984 pn = (dot != -1) ? cn.substring(0, dot).intern() : ""; 985 } 986 this.packageName = pn; 987 } 988 return pn; 989 } 990 991 // cached package name 992 private transient String packageName; 993 994 /** 995 * Returns the interfaces directly implemented by the class or interface 996 * represented by this object. 997 * 998 * <p>If this object represents a class, the return value is an array 999 * containing objects representing all interfaces directly implemented by 1000 * the class. The order of the interface objects in the array corresponds 1001 * to the order of the interface names in the {@code implements} clause of 1002 * the declaration of the class represented by this object. For example, 1003 * given the declaration: 1004 * <blockquote> 1005 * {@code class Shimmer implements FloorWax, DessertTopping { ... }} 1006 * </blockquote> 1007 * suppose the value of {@code s} is an instance of 1008 * {@code Shimmer}; the value of the expression: 1009 * <blockquote> 1010 * {@code s.getClass().getInterfaces()[0]} 1011 * </blockquote> 1012 * is the {@code Class} object that represents interface 1013 * {@code FloorWax}; and the value of: 1014 * <blockquote> 1015 * {@code s.getClass().getInterfaces()[1]} 1016 * </blockquote> 1017 * is the {@code Class} object that represents interface 1018 * {@code DessertTopping}. 1019 * 1020 * <p>If this object represents an interface, the array contains objects 1021 * representing all interfaces directly extended by the interface. The 1022 * order of the interface objects in the array corresponds to the order of 1023 * the interface names in the {@code extends} clause of the declaration of 1024 * the interface represented by this object. 1025 * 1026 * <p>If this object represents a class or interface that implements no 1027 * interfaces, the method returns an array of length 0. 1028 * 1029 * <p>If this object represents a primitive type or void, the method 1030 * returns an array of length 0. 1031 * 1032 * <p>If this {@code Class} object represents an array type, the 1033 * interfaces {@code Cloneable} and {@code java.io.Serializable} are 1034 * returned in that order. 1035 * 1036 * @return an array of interfaces directly implemented by this class 1037 */ 1038 public Class<?>[] getInterfaces() { 1039 // defensively copy before handing over to user code 1040 return getInterfaces(true); 1041 } 1042 1043 private Class<?>[] getInterfaces(boolean cloneArray) { 1044 ReflectionData<T> rd = reflectionData(); 1045 if (rd == null) { 1046 // no cloning required 1047 return getInterfaces0(); 1048 } else { 1049 Class<?>[] interfaces = rd.interfaces; 1050 if (interfaces == null) { 1051 interfaces = getInterfaces0(); 1052 rd.interfaces = interfaces; 1053 } 1054 // defensively copy if requested 1055 return cloneArray ? interfaces.clone() : interfaces; 1056 } 1057 } 1058 1059 private native Class<?>[] getInterfaces0(); 1060 1061 /** 1062 * Returns the {@code Type}s representing the interfaces 1063 * directly implemented by the class or interface represented by 1064 * this object. 1065 * 1066 * <p>If a superinterface is a parameterized type, the 1067 * {@code Type} object returned for it must accurately reflect 1068 * the actual type parameters used in the source code. The 1069 * parameterized type representing each superinterface is created 1070 * if it had not been created before. See the declaration of 1071 * {@link java.lang.reflect.ParameterizedType ParameterizedType} 1072 * for the semantics of the creation process for parameterized 1073 * types. 1074 * 1075 * <p>If this object represents a class, the return value is an array 1076 * containing objects representing all interfaces directly implemented by 1077 * the class. The order of the interface objects in the array corresponds 1078 * to the order of the interface names in the {@code implements} clause of 1079 * the declaration of the class represented by this object. 1080 * 1081 * <p>If this object represents an interface, the array contains objects 1082 * representing all interfaces directly extended by the interface. The 1083 * order of the interface objects in the array corresponds to the order of 1084 * the interface names in the {@code extends} clause of the declaration of 1085 * the interface represented by this object. 1086 * 1087 * <p>If this object represents a class or interface that implements no 1088 * interfaces, the method returns an array of length 0. 1089 * 1090 * <p>If this object represents a primitive type or void, the method 1091 * returns an array of length 0. 1092 * 1093 * <p>If this {@code Class} object represents an array type, the 1094 * interfaces {@code Cloneable} and {@code java.io.Serializable} are 1095 * returned in that order. 1096 * 1097 * @throws java.lang.reflect.GenericSignatureFormatError 1098 * if the generic class signature does not conform to the format 1099 * specified in 1100 * <cite>The Java™ Virtual Machine Specification</cite> 1101 * @throws TypeNotPresentException if any of the generic 1102 * superinterfaces refers to a non-existent type declaration 1103 * @throws java.lang.reflect.MalformedParameterizedTypeException 1104 * if any of the generic superinterfaces refer to a parameterized 1105 * type that cannot be instantiated for any reason 1106 * @return an array of interfaces directly implemented by this class 1107 * @since 1.5 1108 */ 1109 public Type[] getGenericInterfaces() { 1110 ClassRepository info = getGenericInfo(); 1111 return (info == null) ? getInterfaces() : info.getSuperInterfaces(); 1112 } 1113 1114 1115 /** 1116 * Returns the {@code Class} representing the component type of an 1117 * array. If this class does not represent an array class this method 1118 * returns null. 1119 * 1120 * @return the {@code Class} representing the component type of this 1121 * class if this class is an array 1122 * @see java.lang.reflect.Array 1123 * @since 1.1 1124 */ 1125 public Class<?> getComponentType() { 1126 // Only return for array types. Storage may be reused for Class for instance types. 1127 if (isArray()) { 1128 return componentType; 1129 } else { 1130 return null; 1131 } 1132 } 1133 1134 private final Class<?> componentType; 1135 1136 1137 /** 1138 * Returns the Java language modifiers for this class or interface, encoded 1139 * in an integer. The modifiers consist of the Java Virtual Machine's 1140 * constants for {@code public}, {@code protected}, 1141 * {@code private}, {@code final}, {@code static}, 1142 * {@code abstract} and {@code interface}; they should be decoded 1143 * using the methods of class {@code Modifier}. 1144 * 1145 * <p> If the underlying class is an array class, then its 1146 * {@code public}, {@code private} and {@code protected} 1147 * modifiers are the same as those of its component type. If this 1148 * {@code Class} represents a primitive type or void, its 1149 * {@code public} modifier is always {@code true}, and its 1150 * {@code protected} and {@code private} modifiers are always 1151 * {@code false}. If this object represents an array class, a 1152 * primitive type or void, then its {@code final} modifier is always 1153 * {@code true} and its interface modifier is always 1154 * {@code false}. The values of its other modifiers are not determined 1155 * by this specification. 1156 * 1157 * <p> The modifier encodings are defined in <em>The Java Virtual Machine 1158 * Specification</em>, table 4.1. 1159 * 1160 * @return the {@code int} representing the modifiers for this class 1161 * @see java.lang.reflect.Modifier 1162 * @since 1.1 1163 */ 1164 @HotSpotIntrinsicCandidate 1165 public native int getModifiers(); 1166 1167 1168 /** 1169 * Gets the signers of this class. 1170 * 1171 * @return the signers of this class, or null if there are no signers. In 1172 * particular, this method returns null if this object represents 1173 * a primitive type or void. 1174 * @since 1.1 1175 */ 1176 public native Object[] getSigners(); 1177 1178 1179 /** 1180 * Set the signers of this class. 1181 */ 1182 native void setSigners(Object[] signers); 1183 1184 1185 /** 1186 * If this {@code Class} object represents a local or anonymous 1187 * class within a method, returns a {@link 1188 * java.lang.reflect.Method Method} object representing the 1189 * immediately enclosing method of the underlying class. Returns 1190 * {@code null} otherwise. 1191 * 1192 * In particular, this method returns {@code null} if the underlying 1193 * class is a local or anonymous class immediately enclosed by a type 1194 * declaration, instance initializer or static initializer. 1195 * 1196 * @return the immediately enclosing method of the underlying class, if 1197 * that class is a local or anonymous class; otherwise {@code null}. 1198 * 1199 * @throws SecurityException 1200 * If a security manager, <i>s</i>, is present and any of the 1201 * following conditions is met: 1202 * 1203 * <ul> 1204 * 1205 * <li> the caller's class loader is not the same as the 1206 * class loader of the enclosing class and invocation of 1207 * {@link SecurityManager#checkPermission 1208 * s.checkPermission} method with 1209 * {@code RuntimePermission("accessDeclaredMembers")} 1210 * denies access to the methods within the enclosing class 1211 * 1212 * <li> the caller's class loader is not the same as or an 1213 * ancestor of the class loader for the enclosing class and 1214 * invocation of {@link SecurityManager#checkPackageAccess 1215 * s.checkPackageAccess()} denies access to the package 1216 * of the enclosing class 1217 * 1218 * </ul> 1219 * @since 1.5 1220 */ 1221 @CallerSensitive 1222 public Method getEnclosingMethod() throws SecurityException { 1223 EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo(); 1224 1225 if (enclosingInfo == null) 1226 return null; 1227 else { 1228 if (!enclosingInfo.isMethod()) 1229 return null; 1230 1231 MethodRepository typeInfo = MethodRepository.make(enclosingInfo.getDescriptor(), 1232 getFactory()); 1233 Class<?> returnType = toClass(typeInfo.getReturnType()); 1234 Type [] parameterTypes = typeInfo.getParameterTypes(); 1235 Class<?>[] parameterClasses = new Class<?>[parameterTypes.length]; 1236 1237 // Convert Types to Classes; returned types *should* 1238 // be class objects since the methodDescriptor's used 1239 // don't have generics information 1240 for(int i = 0; i < parameterClasses.length; i++) 1241 parameterClasses[i] = toClass(parameterTypes[i]); 1242 1243 // Perform access check 1244 final Class<?> enclosingCandidate = enclosingInfo.getEnclosingClass(); 1245 SecurityManager sm = System.getSecurityManager(); 1246 if (sm != null) { 1247 enclosingCandidate.checkMemberAccess(sm, Member.DECLARED, 1248 Reflection.getCallerClass(), true); 1249 } 1250 Method[] candidates = enclosingCandidate.privateGetDeclaredMethods(false); 1251 1252 /* 1253 * Loop over all declared methods; match method name, 1254 * number of and type of parameters, *and* return 1255 * type. Matching return type is also necessary 1256 * because of covariant returns, etc. 1257 */ 1258 ReflectionFactory fact = getReflectionFactory(); 1259 for (Method m : candidates) { 1260 if (m.getName().equals(enclosingInfo.getName()) && 1261 arrayContentsEq(parameterClasses, 1262 fact.getExecutableSharedParameterTypes(m))) { 1263 // finally, check return type 1264 if (m.getReturnType().equals(returnType)) { 1265 return fact.copyMethod(m); 1266 } 1267 } 1268 } 1269 1270 throw new InternalError("Enclosing method not found"); 1271 } 1272 } 1273 1274 private native Object[] getEnclosingMethod0(); 1275 1276 private EnclosingMethodInfo getEnclosingMethodInfo() { 1277 Object[] enclosingInfo = getEnclosingMethod0(); 1278 if (enclosingInfo == null) 1279 return null; 1280 else { 1281 return new EnclosingMethodInfo(enclosingInfo); 1282 } 1283 } 1284 1285 private static final class EnclosingMethodInfo { 1286 private final Class<?> enclosingClass; 1287 private final String name; 1288 private final String descriptor; 1289 1290 static void validate(Object[] enclosingInfo) { 1291 if (enclosingInfo.length != 3) 1292 throw new InternalError("Malformed enclosing method information"); 1293 try { 1294 // The array is expected to have three elements: 1295 1296 // the immediately enclosing class 1297 Class<?> enclosingClass = (Class<?>)enclosingInfo[0]; 1298 assert(enclosingClass != null); 1299 1300 // the immediately enclosing method or constructor's 1301 // name (can be null). 1302 String name = (String)enclosingInfo[1]; 1303 1304 // the immediately enclosing method or constructor's 1305 // descriptor (null iff name is). 1306 String descriptor = (String)enclosingInfo[2]; 1307 assert((name != null && descriptor != null) || name == descriptor); 1308 } catch (ClassCastException cce) { 1309 throw new InternalError("Invalid type in enclosing method information", cce); 1310 } 1311 } 1312 1313 EnclosingMethodInfo(Object[] enclosingInfo) { 1314 validate(enclosingInfo); 1315 this.enclosingClass = (Class<?>)enclosingInfo[0]; 1316 this.name = (String)enclosingInfo[1]; 1317 this.descriptor = (String)enclosingInfo[2]; 1318 } 1319 1320 boolean isPartial() { 1321 return enclosingClass == null || name == null || descriptor == null; 1322 } 1323 1324 boolean isConstructor() { return !isPartial() && "<init>".equals(name); } 1325 1326 boolean isMethod() { return !isPartial() && !isConstructor() && !"<clinit>".equals(name); } 1327 1328 Class<?> getEnclosingClass() { return enclosingClass; } 1329 1330 String getName() { return name; } 1331 1332 String getDescriptor() { return descriptor; } 1333 1334 } 1335 1336 private static Class<?> toClass(Type o) { 1337 if (o instanceof GenericArrayType) 1338 return Array.newInstance(toClass(((GenericArrayType)o).getGenericComponentType()), 1339 0) 1340 .getClass(); 1341 return (Class<?>)o; 1342 } 1343 1344 /** 1345 * If this {@code Class} object represents a local or anonymous 1346 * class within a constructor, returns a {@link 1347 * java.lang.reflect.Constructor Constructor} object representing 1348 * the immediately enclosing constructor of the underlying 1349 * class. Returns {@code null} otherwise. In particular, this 1350 * method returns {@code null} if the underlying class is a local 1351 * or anonymous class immediately enclosed by a type declaration, 1352 * instance initializer or static initializer. 1353 * 1354 * @return the immediately enclosing constructor of the underlying class, if 1355 * that class is a local or anonymous class; otherwise {@code null}. 1356 * @throws SecurityException 1357 * If a security manager, <i>s</i>, is present and any of the 1358 * following conditions is met: 1359 * 1360 * <ul> 1361 * 1362 * <li> the caller's class loader is not the same as the 1363 * class loader of the enclosing class and invocation of 1364 * {@link SecurityManager#checkPermission 1365 * s.checkPermission} method with 1366 * {@code RuntimePermission("accessDeclaredMembers")} 1367 * denies access to the constructors within the enclosing class 1368 * 1369 * <li> the caller's class loader is not the same as or an 1370 * ancestor of the class loader for the enclosing class and 1371 * invocation of {@link SecurityManager#checkPackageAccess 1372 * s.checkPackageAccess()} denies access to the package 1373 * of the enclosing class 1374 * 1375 * </ul> 1376 * @since 1.5 1377 */ 1378 @CallerSensitive 1379 public Constructor<?> getEnclosingConstructor() throws SecurityException { 1380 EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo(); 1381 1382 if (enclosingInfo == null) 1383 return null; 1384 else { 1385 if (!enclosingInfo.isConstructor()) 1386 return null; 1387 1388 ConstructorRepository typeInfo = ConstructorRepository.make(enclosingInfo.getDescriptor(), 1389 getFactory()); 1390 Type [] parameterTypes = typeInfo.getParameterTypes(); 1391 Class<?>[] parameterClasses = new Class<?>[parameterTypes.length]; 1392 1393 // Convert Types to Classes; returned types *should* 1394 // be class objects since the methodDescriptor's used 1395 // don't have generics information 1396 for(int i = 0; i < parameterClasses.length; i++) 1397 parameterClasses[i] = toClass(parameterTypes[i]); 1398 1399 // Perform access check 1400 final Class<?> enclosingCandidate = enclosingInfo.getEnclosingClass(); 1401 SecurityManager sm = System.getSecurityManager(); 1402 if (sm != null) { 1403 enclosingCandidate.checkMemberAccess(sm, Member.DECLARED, 1404 Reflection.getCallerClass(), true); 1405 } 1406 1407 Constructor<?>[] candidates = enclosingCandidate 1408 .privateGetDeclaredConstructors(false); 1409 /* 1410 * Loop over all declared constructors; match number 1411 * of and type of parameters. 1412 */ 1413 ReflectionFactory fact = getReflectionFactory(); 1414 for (Constructor<?> c : candidates) { 1415 if (arrayContentsEq(parameterClasses, 1416 fact.getExecutableSharedParameterTypes(c))) { 1417 return fact.copyConstructor(c); 1418 } 1419 } 1420 1421 throw new InternalError("Enclosing constructor not found"); 1422 } 1423 } 1424 1425 1426 /** 1427 * If the class or interface represented by this {@code Class} object 1428 * is a member of another class, returns the {@code Class} object 1429 * representing the class in which it was declared. This method returns 1430 * null if this class or interface is not a member of any other class. If 1431 * this {@code Class} object represents an array class, a primitive 1432 * type, or void,then this method returns null. 1433 * 1434 * @return the declaring class for this class 1435 * @throws SecurityException 1436 * If a security manager, <i>s</i>, is present and the caller's 1437 * class loader is not the same as or an ancestor of the class 1438 * loader for the declaring class and invocation of {@link 1439 * SecurityManager#checkPackageAccess s.checkPackageAccess()} 1440 * denies access to the package of the declaring class 1441 * @since 1.1 1442 */ 1443 @CallerSensitive 1444 public Class<?> getDeclaringClass() throws SecurityException { 1445 final Class<?> candidate = getDeclaringClass0(); 1446 1447 if (candidate != null) { 1448 SecurityManager sm = System.getSecurityManager(); 1449 if (sm != null) { 1450 candidate.checkPackageAccess(sm, 1451 ClassLoader.getClassLoader(Reflection.getCallerClass()), true); 1452 } 1453 } 1454 return candidate; 1455 } 1456 1457 private native Class<?> getDeclaringClass0(); 1458 1459 1460 /** 1461 * Returns the immediately enclosing class of the underlying 1462 * class. If the underlying class is a top level class this 1463 * method returns {@code null}. 1464 * @return the immediately enclosing class of the underlying class 1465 * @exception SecurityException 1466 * If a security manager, <i>s</i>, is present and the caller's 1467 * class loader is not the same as or an ancestor of the class 1468 * loader for the enclosing class and invocation of {@link 1469 * SecurityManager#checkPackageAccess s.checkPackageAccess()} 1470 * denies access to the package of the enclosing class 1471 * @since 1.5 1472 */ 1473 @CallerSensitive 1474 public Class<?> getEnclosingClass() throws SecurityException { 1475 // There are five kinds of classes (or interfaces): 1476 // a) Top level classes 1477 // b) Nested classes (static member classes) 1478 // c) Inner classes (non-static member classes) 1479 // d) Local classes (named classes declared within a method) 1480 // e) Anonymous classes 1481 1482 1483 // JVM Spec 4.7.7: A class must have an EnclosingMethod 1484 // attribute if and only if it is a local class or an 1485 // anonymous class. 1486 EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo(); 1487 Class<?> enclosingCandidate; 1488 1489 if (enclosingInfo == null) { 1490 // This is a top level or a nested class or an inner class (a, b, or c) 1491 enclosingCandidate = getDeclaringClass0(); 1492 } else { 1493 Class<?> enclosingClass = enclosingInfo.getEnclosingClass(); 1494 // This is a local class or an anonymous class (d or e) 1495 if (enclosingClass == this || enclosingClass == null) 1496 throw new InternalError("Malformed enclosing method information"); 1497 else 1498 enclosingCandidate = enclosingClass; 1499 } 1500 1501 if (enclosingCandidate != null) { 1502 SecurityManager sm = System.getSecurityManager(); 1503 if (sm != null) { 1504 enclosingCandidate.checkPackageAccess(sm, 1505 ClassLoader.getClassLoader(Reflection.getCallerClass()), true); 1506 } 1507 } 1508 return enclosingCandidate; 1509 } 1510 1511 /** 1512 * Returns the simple name of the underlying class as given in the 1513 * source code. Returns an empty string if the underlying class is 1514 * anonymous. 1515 * 1516 * <p>The simple name of an array is the simple name of the 1517 * component type with "[]" appended. In particular the simple 1518 * name of an array whose component type is anonymous is "[]". 1519 * 1520 * @return the simple name of the underlying class 1521 * @since 1.5 1522 */ 1523 public String getSimpleName() { 1524 if (isArray()) 1525 return getComponentType().getSimpleName()+"[]"; 1526 1527 String simpleName = getSimpleBinaryName(); 1528 if (simpleName == null) { // top level class 1529 simpleName = getName(); 1530 return simpleName.substring(simpleName.lastIndexOf('.')+1); // strip the package name 1531 } 1532 return simpleName; 1533 } 1534 1535 /** 1536 * Return an informative string for the name of this type. 1537 * 1538 * @return an informative string for the name of this type 1539 * @since 1.8 1540 */ 1541 public String getTypeName() { 1542 if (isArray()) { 1543 try { 1544 Class<?> cl = this; 1545 int dimensions = 0; 1546 while (cl.isArray()) { 1547 dimensions++; 1548 cl = cl.getComponentType(); 1549 } 1550 StringBuilder sb = new StringBuilder(); 1551 sb.append(cl.getName()); 1552 for (int i = 0; i < dimensions; i++) { 1553 sb.append("[]"); 1554 } 1555 return sb.toString(); 1556 } catch (Throwable e) { /*FALLTHRU*/ } 1557 } 1558 return getName(); 1559 } 1560 1561 /** 1562 * Returns the canonical name of the underlying class as 1563 * defined by the Java Language Specification. Returns null if 1564 * the underlying class does not have a canonical name (i.e., if 1565 * it is a local or anonymous class or an array whose component 1566 * type does not have a canonical name). 1567 * @return the canonical name of the underlying class if it exists, and 1568 * {@code null} otherwise. 1569 * @since 1.5 1570 */ 1571 public String getCanonicalName() { 1572 if (isArray()) { 1573 String canonicalName = getComponentType().getCanonicalName(); 1574 if (canonicalName != null) 1575 return canonicalName + "[]"; 1576 else 1577 return null; 1578 } 1579 if (isLocalOrAnonymousClass()) 1580 return null; 1581 Class<?> enclosingClass = getEnclosingClass(); 1582 if (enclosingClass == null) { // top level class 1583 return getName(); 1584 } else { 1585 String enclosingName = enclosingClass.getCanonicalName(); 1586 if (enclosingName == null) 1587 return null; 1588 return enclosingName + "." + getSimpleName(); 1589 } 1590 } 1591 1592 /** 1593 * Returns {@code true} if and only if the underlying class 1594 * is an anonymous class. 1595 * 1596 * @return {@code true} if and only if this class is an anonymous class. 1597 * @since 1.5 1598 */ 1599 public boolean isAnonymousClass() { 1600 return !isArray() && isLocalOrAnonymousClass() && 1601 getSimpleBinaryName0() == null; 1602 } 1603 1604 /** 1605 * Returns {@code true} if and only if the underlying class 1606 * is a local class. 1607 * 1608 * @return {@code true} if and only if this class is a local class. 1609 * @since 1.5 1610 */ 1611 public boolean isLocalClass() { 1612 return isLocalOrAnonymousClass() && 1613 (isArray() || getSimpleBinaryName0() != null); 1614 } 1615 1616 /** 1617 * Returns {@code true} if and only if the underlying class 1618 * is a member class. 1619 * 1620 * @return {@code true} if and only if this class is a member class. 1621 * @since 1.5 1622 */ 1623 public boolean isMemberClass() { 1624 return !isLocalOrAnonymousClass() && getDeclaringClass0() != null; 1625 } 1626 1627 /** 1628 * Returns the "simple binary name" of the underlying class, i.e., 1629 * the binary name without the leading enclosing class name. 1630 * Returns {@code null} if the underlying class is a top level 1631 * class. 1632 */ 1633 private String getSimpleBinaryName() { 1634 if (isTopLevelClass()) 1635 return null; 1636 String name = getSimpleBinaryName0(); 1637 if (name == null) // anonymous class 1638 return ""; 1639 return name; 1640 } 1641 1642 private native String getSimpleBinaryName0(); 1643 1644 /** 1645 * Returns {@code true} if this is a top level class. Returns {@code false} 1646 * otherwise. 1647 */ 1648 private boolean isTopLevelClass() { 1649 return !isLocalOrAnonymousClass() && getDeclaringClass0() == null; 1650 } 1651 1652 /** 1653 * Returns {@code true} if this is a local class or an anonymous 1654 * class. Returns {@code false} otherwise. 1655 */ 1656 private boolean isLocalOrAnonymousClass() { 1657 // JVM Spec 4.7.7: A class must have an EnclosingMethod 1658 // attribute if and only if it is a local class or an 1659 // anonymous class. 1660 return hasEnclosingMethodInfo(); 1661 } 1662 1663 private boolean hasEnclosingMethodInfo() { 1664 Object[] enclosingInfo = getEnclosingMethod0(); 1665 if (enclosingInfo != null) { 1666 EnclosingMethodInfo.validate(enclosingInfo); 1667 return true; 1668 } 1669 return false; 1670 } 1671 1672 /** 1673 * Returns an array containing {@code Class} objects representing all 1674 * the public classes and interfaces that are members of the class 1675 * represented by this {@code Class} object. This includes public 1676 * class and interface members inherited from superclasses and public class 1677 * and interface members declared by the class. This method returns an 1678 * array of length 0 if this {@code Class} object has no public member 1679 * classes or interfaces. This method also returns an array of length 0 if 1680 * this {@code Class} object represents a primitive type, an array 1681 * class, or void. 1682 * 1683 * @return the array of {@code Class} objects representing the public 1684 * members of this class 1685 * @throws SecurityException 1686 * If a security manager, <i>s</i>, is present and 1687 * the caller's class loader is not the same as or an 1688 * ancestor of the class loader for the current class and 1689 * invocation of {@link SecurityManager#checkPackageAccess 1690 * s.checkPackageAccess()} denies access to the package 1691 * of this class. 1692 * 1693 * @since 1.1 1694 */ 1695 @CallerSensitive 1696 public Class<?>[] getClasses() { 1697 SecurityManager sm = System.getSecurityManager(); 1698 if (sm != null) { 1699 checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), false); 1700 } 1701 1702 // Privileged so this implementation can look at DECLARED classes, 1703 // something the caller might not have privilege to do. The code here 1704 // is allowed to look at DECLARED classes because (1) it does not hand 1705 // out anything other than public members and (2) public member access 1706 // has already been ok'd by the SecurityManager. 1707 1708 return java.security.AccessController.doPrivileged( 1709 new java.security.PrivilegedAction<>() { 1710 public Class<?>[] run() { 1711 List<Class<?>> list = new ArrayList<>(); 1712 Class<?> currentClass = Class.this; 1713 while (currentClass != null) { 1714 for (Class<?> m : currentClass.getDeclaredClasses()) { 1715 if (Modifier.isPublic(m.getModifiers())) { 1716 list.add(m); 1717 } 1718 } 1719 currentClass = currentClass.getSuperclass(); 1720 } 1721 return list.toArray(new Class<?>[0]); 1722 } 1723 }); 1724 } 1725 1726 1727 /** 1728 * Returns an array containing {@code Field} objects reflecting all 1729 * the accessible public fields of the class or interface represented by 1730 * this {@code Class} object. 1731 * 1732 * <p> If this {@code Class} object represents a class or interface with 1733 * no accessible public fields, then this method returns an array of length 1734 * 0. 1735 * 1736 * <p> If this {@code Class} object represents a class, then this method 1737 * returns the public fields of the class and of all its superclasses and 1738 * superinterfaces. 1739 * 1740 * <p> If this {@code Class} object represents an interface, then this 1741 * method returns the fields of the interface and of all its 1742 * superinterfaces. 1743 * 1744 * <p> If this {@code Class} object represents an array type, a primitive 1745 * type, or void, then this method returns an array of length 0. 1746 * 1747 * <p> The elements in the returned array are not sorted and are not in any 1748 * particular order. 1749 * 1750 * @return the array of {@code Field} objects representing the 1751 * public fields 1752 * @throws SecurityException 1753 * If a security manager, <i>s</i>, is present and 1754 * the caller's class loader is not the same as or an 1755 * ancestor of the class loader for the current class and 1756 * invocation of {@link SecurityManager#checkPackageAccess 1757 * s.checkPackageAccess()} denies access to the package 1758 * of this class. 1759 * 1760 * @since 1.1 1761 * @jls 8.2 Class Members 1762 * @jls 8.3 Field Declarations 1763 */ 1764 @CallerSensitive 1765 public Field[] getFields() throws SecurityException { 1766 SecurityManager sm = System.getSecurityManager(); 1767 if (sm != null) { 1768 checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true); 1769 } 1770 return copyFields(privateGetPublicFields(null)); 1771 } 1772 1773 1774 /** 1775 * Returns an array containing {@code Method} objects reflecting all the 1776 * public methods of the class or interface represented by this {@code 1777 * Class} object, including those declared by the class or interface and 1778 * those inherited from superclasses and superinterfaces. 1779 * 1780 * <p> If this {@code Class} object represents an array type, then the 1781 * returned array has a {@code Method} object for each of the public 1782 * methods inherited by the array type from {@code Object}. It does not 1783 * contain a {@code Method} object for {@code clone()}. 1784 * 1785 * <p> If this {@code Class} object represents an interface then the 1786 * returned array does not contain any implicitly declared methods from 1787 * {@code Object}. Therefore, if no methods are explicitly declared in 1788 * this interface or any of its superinterfaces then the returned array 1789 * has length 0. (Note that a {@code Class} object which represents a class 1790 * always has public methods, inherited from {@code Object}.) 1791 * 1792 * <p> The returned array never contains methods with names "{@code <init>}" 1793 * or "{@code <clinit>}". 1794 * 1795 * <p> The elements in the returned array are not sorted and are not in any 1796 * particular order. 1797 * 1798 * <p> Generally, the result is computed as with the following 4 step algorithm. 1799 * Let C be the class or interface represented by this {@code Class} object: 1800 * <ol> 1801 * <li> A union of methods is composed of: 1802 * <ol type="a"> 1803 * <li> C's declared public instance and static methods as returned by 1804 * {@link #getDeclaredMethods()} and filtered to include only public 1805 * methods.</li> 1806 * <li> If C is a class other than {@code Object}, then include the result 1807 * of invoking this algorithm recursively on the superclass of C.</li> 1808 * <li> Include the results of invoking this algorithm recursively on all 1809 * direct superinterfaces of C, but include only instance methods.</li> 1810 * </ol></li> 1811 * <li> Union from step 1 is partitioned into subsets of methods with same 1812 * signature (name, parameter types) and return type.</li> 1813 * <li> Within each such subset only the most specific methods are selected. 1814 * Let method M be a method from a set of methods with same signature 1815 * and return type. M is most specific if there is no such method 1816 * N != M from the same set, such that N is more specific than M. 1817 * N is more specific than M if: 1818 * <ol type="a"> 1819 * <li> N is declared by a class and M is declared by an interface; or</li> 1820 * <li> N and M are both declared by classes or both by interfaces and 1821 * N's declaring type is the same as or a subtype of M's declaring type 1822 * (clearly, if M's and N's declaring types are the same type, then 1823 * M and N are the same method).</li> 1824 * </ol></li> 1825 * <li> The result of this algorithm is the union of all selected methods from 1826 * step 3.</li> 1827 * </ol> 1828 * 1829 * @apiNote There may be more than one method with a particular name 1830 * and parameter types in a class because while the Java language forbids a 1831 * class to declare multiple methods with the same signature but different 1832 * return types, the Java virtual machine does not. This 1833 * increased flexibility in the virtual machine can be used to 1834 * implement various language features. For example, covariant 1835 * returns can be implemented with {@linkplain 1836 * java.lang.reflect.Method#isBridge bridge methods}; the bridge 1837 * method and the overriding method would have the same 1838 * signature but different return types. 1839 * 1840 * @return the array of {@code Method} objects representing the 1841 * public methods of this class 1842 * @throws SecurityException 1843 * If a security manager, <i>s</i>, is present and 1844 * the caller's class loader is not the same as or an 1845 * ancestor of the class loader for the current class and 1846 * invocation of {@link SecurityManager#checkPackageAccess 1847 * s.checkPackageAccess()} denies access to the package 1848 * of this class. 1849 * 1850 * @jls 8.2 Class Members 1851 * @jls 8.4 Method Declarations 1852 * @since 1.1 1853 */ 1854 @CallerSensitive 1855 public Method[] getMethods() throws SecurityException { 1856 SecurityManager sm = System.getSecurityManager(); 1857 if (sm != null) { 1858 checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true); 1859 } 1860 return copyMethods(privateGetPublicMethods()); 1861 } 1862 1863 1864 /** 1865 * Returns an array containing {@code Constructor} objects reflecting 1866 * all the public constructors of the class represented by this 1867 * {@code Class} object. An array of length 0 is returned if the 1868 * class has no public constructors, or if the class is an array class, or 1869 * if the class reflects a primitive type or void. 1870 * 1871 * Note that while this method returns an array of {@code 1872 * Constructor<T>} objects (that is an array of constructors from 1873 * this class), the return type of this method is {@code 1874 * Constructor<?>[]} and <em>not</em> {@code Constructor<T>[]} as 1875 * might be expected. This less informative return type is 1876 * necessary since after being returned from this method, the 1877 * array could be modified to hold {@code Constructor} objects for 1878 * different classes, which would violate the type guarantees of 1879 * {@code Constructor<T>[]}. 1880 * 1881 * @return the array of {@code Constructor} objects representing the 1882 * public constructors of this class 1883 * @throws SecurityException 1884 * If a security manager, <i>s</i>, is present and 1885 * the caller's class loader is not the same as or an 1886 * ancestor of the class loader for the current class and 1887 * invocation of {@link SecurityManager#checkPackageAccess 1888 * s.checkPackageAccess()} denies access to the package 1889 * of this class. 1890 * 1891 * @since 1.1 1892 */ 1893 @CallerSensitive 1894 public Constructor<?>[] getConstructors() throws SecurityException { 1895 SecurityManager sm = System.getSecurityManager(); 1896 if (sm != null) { 1897 checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true); 1898 } 1899 return copyConstructors(privateGetDeclaredConstructors(true)); 1900 } 1901 1902 1903 /** 1904 * Returns a {@code Field} object that reflects the specified public member 1905 * field of the class or interface represented by this {@code Class} 1906 * object. The {@code name} parameter is a {@code String} specifying the 1907 * simple name of the desired field. 1908 * 1909 * <p> The field to be reflected is determined by the algorithm that 1910 * follows. Let C be the class or interface represented by this object: 1911 * 1912 * <OL> 1913 * <LI> If C declares a public field with the name specified, that is the 1914 * field to be reflected.</LI> 1915 * <LI> If no field was found in step 1 above, this algorithm is applied 1916 * recursively to each direct superinterface of C. The direct 1917 * superinterfaces are searched in the order they were declared.</LI> 1918 * <LI> If no field was found in steps 1 and 2 above, and C has a 1919 * superclass S, then this algorithm is invoked recursively upon S. 1920 * If C has no superclass, then a {@code NoSuchFieldException} 1921 * is thrown.</LI> 1922 * </OL> 1923 * 1924 * <p> If this {@code Class} object represents an array type, then this 1925 * method does not find the {@code length} field of the array type. 1926 * 1927 * @param name the field name 1928 * @return the {@code Field} object of this class specified by 1929 * {@code name} 1930 * @throws NoSuchFieldException if a field with the specified name is 1931 * not found. 1932 * @throws NullPointerException if {@code name} is {@code null} 1933 * @throws SecurityException 1934 * If a security manager, <i>s</i>, is present and 1935 * the caller's class loader is not the same as or an 1936 * ancestor of the class loader for the current class and 1937 * invocation of {@link SecurityManager#checkPackageAccess 1938 * s.checkPackageAccess()} denies access to the package 1939 * of this class. 1940 * 1941 * @since 1.1 1942 * @jls 8.2 Class Members 1943 * @jls 8.3 Field Declarations 1944 */ 1945 @CallerSensitive 1946 public Field getField(String name) 1947 throws NoSuchFieldException, SecurityException { 1948 Objects.requireNonNull(name); 1949 SecurityManager sm = System.getSecurityManager(); 1950 if (sm != null) { 1951 checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true); 1952 } 1953 Field field = getField0(name); 1954 if (field == null) { 1955 throw new NoSuchFieldException(name); 1956 } 1957 return getReflectionFactory().copyField(field); 1958 } 1959 1960 1961 /** 1962 * Returns a {@code Method} object that reflects the specified public 1963 * member method of the class or interface represented by this 1964 * {@code Class} object. The {@code name} parameter is a 1965 * {@code String} specifying the simple name of the desired method. The 1966 * {@code parameterTypes} parameter is an array of {@code Class} 1967 * objects that identify the method's formal parameter types, in declared 1968 * order. If {@code parameterTypes} is {@code null}, it is 1969 * treated as if it were an empty array. 1970 * 1971 * <p> If this {@code Class} object represents an array type, then this 1972 * method finds any public method inherited by the array type from 1973 * {@code Object} except method {@code clone()}. 1974 * 1975 * <p> If this {@code Class} object represents an interface then this 1976 * method does not find any implicitly declared method from 1977 * {@code Object}. Therefore, if no methods are explicitly declared in 1978 * this interface or any of its superinterfaces, then this method does not 1979 * find any method. 1980 * 1981 * <p> This method does not find any method with name "{@code <init>}" or 1982 * "{@code <clinit>}". 1983 * 1984 * <p> Generally, the method to be reflected is determined by the 4 step 1985 * algorithm that follows. 1986 * Let C be the class or interface represented by this {@code Class} object: 1987 * <ol> 1988 * <li> A union of methods is composed of: 1989 * <ol type="a"> 1990 * <li> C's declared public instance and static methods as returned by 1991 * {@link #getDeclaredMethods()} and filtered to include only public 1992 * methods that match given {@code name} and {@code parameterTypes}</li> 1993 * <li> If C is a class other than {@code Object}, then include the result 1994 * of invoking this algorithm recursively on the superclass of C.</li> 1995 * <li> Include the results of invoking this algorithm recursively on all 1996 * direct superinterfaces of C, but include only instance methods.</li> 1997 * </ol></li> 1998 * <li> This union is partitioned into subsets of methods with same 1999 * return type (the selection of methods from step 1 also guarantees that 2000 * they have the same method name and parameter types).</li> 2001 * <li> Within each such subset only the most specific methods are selected. 2002 * Let method M be a method from a set of methods with same VM 2003 * signature (return type, name, parameter types). 2004 * M is most specific if there is no such method N != M from the same 2005 * set, such that N is more specific than M. N is more specific than M 2006 * if: 2007 * <ol type="a"> 2008 * <li> N is declared by a class and M is declared by an interface; or</li> 2009 * <li> N and M are both declared by classes or both by interfaces and 2010 * N's declaring type is the same as or a subtype of M's declaring type 2011 * (clearly, if M's and N's declaring types are the same type, then 2012 * M and N are the same method).</li> 2013 * </ol></li> 2014 * <li> The result of this algorithm is chosen arbitrarily from the methods 2015 * with most specific return type among all selected methods from step 3. 2016 * Let R be a return type of a method M from the set of all selected methods 2017 * from step 3. M is a method with most specific return type if there is 2018 * no such method N != M from the same set, having return type S != R, 2019 * such that S is a subtype of R as determined by 2020 * R.class.{@link #isAssignableFrom}(S.class). 2021 * </ol> 2022 * 2023 * @apiNote There may be more than one method with matching name and 2024 * parameter types in a class because while the Java language forbids a 2025 * class to declare multiple methods with the same signature but different 2026 * return types, the Java virtual machine does not. This 2027 * increased flexibility in the virtual machine can be used to 2028 * implement various language features. For example, covariant 2029 * returns can be implemented with {@linkplain 2030 * java.lang.reflect.Method#isBridge bridge methods}; the bridge 2031 * method and the overriding method would have the same 2032 * signature but different return types. This method would return the 2033 * overriding method as it would have a more specific return type. 2034 * 2035 * @param name the name of the method 2036 * @param parameterTypes the list of parameters 2037 * @return the {@code Method} object that matches the specified 2038 * {@code name} and {@code parameterTypes} 2039 * @throws NoSuchMethodException if a matching method is not found 2040 * or if the name is "<init>"or "<clinit>". 2041 * @throws NullPointerException if {@code name} is {@code null} 2042 * @throws SecurityException 2043 * If a security manager, <i>s</i>, is present and 2044 * the caller's class loader is not the same as or an 2045 * ancestor of the class loader for the current class and 2046 * invocation of {@link SecurityManager#checkPackageAccess 2047 * s.checkPackageAccess()} denies access to the package 2048 * of this class. 2049 * 2050 * @jls 8.2 Class Members 2051 * @jls 8.4 Method Declarations 2052 * @since 1.1 2053 */ 2054 @CallerSensitive 2055 public Method getMethod(String name, Class<?>... parameterTypes) 2056 throws NoSuchMethodException, SecurityException { 2057 Objects.requireNonNull(name); 2058 SecurityManager sm = System.getSecurityManager(); 2059 if (sm != null) { 2060 checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true); 2061 } 2062 Method method = getMethod0(name, parameterTypes); 2063 if (method == null) { 2064 throw new NoSuchMethodException(methodToString(name, parameterTypes)); 2065 } 2066 return getReflectionFactory().copyMethod(method); 2067 } 2068 2069 /** 2070 * Returns a {@code Method} object that reflects the specified public 2071 * member method of the class or interface represented by this 2072 * {@code Class} object. 2073 * 2074 * @param name the name of the method 2075 * @param parameterTypes the list of parameters 2076 * @return the {@code Method} object that matches the specified 2077 * {@code name} and {@code parameterTypes}; {@code null} 2078 * if the method is not found or the name is 2079 * "<init>"or "<clinit>". 2080 */ 2081 Method getMethodOrNull(String name, Class<?>... parameterTypes) { 2082 Objects.requireNonNull(name); 2083 Method method = getMethod0(name, parameterTypes); 2084 return method == null ? null : getReflectionFactory().copyMethod(method); 2085 } 2086 2087 2088 /** 2089 * Returns a {@code Constructor} object that reflects the specified 2090 * public constructor of the class represented by this {@code Class} 2091 * object. The {@code parameterTypes} parameter is an array of 2092 * {@code Class} objects that identify the constructor's formal 2093 * parameter types, in declared order. 2094 * 2095 * If this {@code Class} object represents an inner class 2096 * declared in a non-static context, the formal parameter types 2097 * include the explicit enclosing instance as the first parameter. 2098 * 2099 * <p> The constructor to reflect is the public constructor of the class 2100 * represented by this {@code Class} object whose formal parameter 2101 * types match those specified by {@code parameterTypes}. 2102 * 2103 * @param parameterTypes the parameter array 2104 * @return the {@code Constructor} object of the public constructor that 2105 * matches the specified {@code parameterTypes} 2106 * @throws NoSuchMethodException if a matching method is not found. 2107 * @throws SecurityException 2108 * If a security manager, <i>s</i>, is present and 2109 * the caller's class loader is not the same as or an 2110 * ancestor of the class loader for the current class and 2111 * invocation of {@link SecurityManager#checkPackageAccess 2112 * s.checkPackageAccess()} denies access to the package 2113 * of this class. 2114 * 2115 * @since 1.1 2116 */ 2117 @CallerSensitive 2118 public Constructor<T> getConstructor(Class<?>... parameterTypes) 2119 throws NoSuchMethodException, SecurityException 2120 { 2121 SecurityManager sm = System.getSecurityManager(); 2122 if (sm != null) { 2123 checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true); 2124 } 2125 return getReflectionFactory().copyConstructor( 2126 getConstructor0(parameterTypes, Member.PUBLIC)); 2127 } 2128 2129 2130 /** 2131 * Returns an array of {@code Class} objects reflecting all the 2132 * classes and interfaces declared as members of the class represented by 2133 * this {@code Class} object. This includes public, protected, default 2134 * (package) access, and private classes and interfaces declared by the 2135 * class, but excludes inherited classes and interfaces. This method 2136 * returns an array of length 0 if the class declares no classes or 2137 * interfaces as members, or if this {@code Class} object represents a 2138 * primitive type, an array class, or void. 2139 * 2140 * @return the array of {@code Class} objects representing all the 2141 * declared members of this class 2142 * @throws SecurityException 2143 * If a security manager, <i>s</i>, is present and any of the 2144 * following conditions is met: 2145 * 2146 * <ul> 2147 * 2148 * <li> the caller's class loader is not the same as the 2149 * class loader of this class and invocation of 2150 * {@link SecurityManager#checkPermission 2151 * s.checkPermission} method with 2152 * {@code RuntimePermission("accessDeclaredMembers")} 2153 * denies access to the declared classes within this class 2154 * 2155 * <li> the caller's class loader is not the same as or an 2156 * ancestor of the class loader for the current class and 2157 * invocation of {@link SecurityManager#checkPackageAccess 2158 * s.checkPackageAccess()} denies access to the package 2159 * of this class 2160 * 2161 * </ul> 2162 * 2163 * @since 1.1 2164 */ 2165 @CallerSensitive 2166 public Class<?>[] getDeclaredClasses() throws SecurityException { 2167 SecurityManager sm = System.getSecurityManager(); 2168 if (sm != null) { 2169 checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), false); 2170 } 2171 return getDeclaredClasses0(); 2172 } 2173 2174 2175 /** 2176 * Returns an array of {@code Field} objects reflecting all the fields 2177 * declared by the class or interface represented by this 2178 * {@code Class} object. This includes public, protected, default 2179 * (package) access, and private fields, but excludes inherited fields. 2180 * 2181 * <p> If this {@code Class} object represents a class or interface with no 2182 * declared fields, then this method returns an array of length 0. 2183 * 2184 * <p> If this {@code Class} object represents an array type, a primitive 2185 * type, or void, then this method returns an array of length 0. 2186 * 2187 * <p> The elements in the returned array are not sorted and are not in any 2188 * particular order. 2189 * 2190 * @return the array of {@code Field} objects representing all the 2191 * declared fields of this class 2192 * @throws SecurityException 2193 * If a security manager, <i>s</i>, is present and any of the 2194 * following conditions is met: 2195 * 2196 * <ul> 2197 * 2198 * <li> the caller's class loader is not the same as the 2199 * class loader of this class and invocation of 2200 * {@link SecurityManager#checkPermission 2201 * s.checkPermission} method with 2202 * {@code RuntimePermission("accessDeclaredMembers")} 2203 * denies access to the declared fields within this class 2204 * 2205 * <li> the caller's class loader is not the same as or an 2206 * ancestor of the class loader for the current class and 2207 * invocation of {@link SecurityManager#checkPackageAccess 2208 * s.checkPackageAccess()} denies access to the package 2209 * of this class 2210 * 2211 * </ul> 2212 * 2213 * @since 1.1 2214 * @jls 8.2 Class Members 2215 * @jls 8.3 Field Declarations 2216 */ 2217 @CallerSensitive 2218 public Field[] getDeclaredFields() throws SecurityException { 2219 SecurityManager sm = System.getSecurityManager(); 2220 if (sm != null) { 2221 checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true); 2222 } 2223 return copyFields(privateGetDeclaredFields(false)); 2224 } 2225 2226 2227 /** 2228 * 2229 * Returns an array containing {@code Method} objects reflecting all the 2230 * declared methods of the class or interface represented by this {@code 2231 * Class} object, including public, protected, default (package) 2232 * access, and private methods, but excluding inherited methods. 2233 * 2234 * <p> If this {@code Class} object represents a type that has multiple 2235 * declared methods with the same name and parameter types, but different 2236 * return types, then the returned array has a {@code Method} object for 2237 * each such method. 2238 * 2239 * <p> If this {@code Class} object represents a type that has a class 2240 * initialization method {@code <clinit>}, then the returned array does 2241 * <em>not</em> have a corresponding {@code Method} object. 2242 * 2243 * <p> If this {@code Class} object represents a class or interface with no 2244 * declared methods, then the returned array has length 0. 2245 * 2246 * <p> If this {@code Class} object represents an array type, a primitive 2247 * type, or void, then the returned array has length 0. 2248 * 2249 * <p> The elements in the returned array are not sorted and are not in any 2250 * particular order. 2251 * 2252 * @return the array of {@code Method} objects representing all the 2253 * declared methods of this class 2254 * @throws SecurityException 2255 * If a security manager, <i>s</i>, is present and any of the 2256 * following conditions is met: 2257 * 2258 * <ul> 2259 * 2260 * <li> the caller's class loader is not the same as the 2261 * class loader of this class and invocation of 2262 * {@link SecurityManager#checkPermission 2263 * s.checkPermission} method with 2264 * {@code RuntimePermission("accessDeclaredMembers")} 2265 * denies access to the declared methods within this class 2266 * 2267 * <li> the caller's class loader is not the same as or an 2268 * ancestor of the class loader for the current class and 2269 * invocation of {@link SecurityManager#checkPackageAccess 2270 * s.checkPackageAccess()} denies access to the package 2271 * of this class 2272 * 2273 * </ul> 2274 * 2275 * @jls 8.2 Class Members 2276 * @jls 8.4 Method Declarations 2277 * @since 1.1 2278 */ 2279 @CallerSensitive 2280 public Method[] getDeclaredMethods() throws SecurityException { 2281 SecurityManager sm = System.getSecurityManager(); 2282 if (sm != null) { 2283 checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true); 2284 } 2285 return copyMethods(privateGetDeclaredMethods(false)); 2286 } 2287 2288 2289 /** 2290 * Returns an array of {@code Constructor} objects reflecting all the 2291 * constructors declared by the class represented by this 2292 * {@code Class} object. These are public, protected, default 2293 * (package) access, and private constructors. The elements in the array 2294 * returned are not sorted and are not in any particular order. If the 2295 * class has a default constructor, it is included in the returned array. 2296 * This method returns an array of length 0 if this {@code Class} 2297 * object represents an interface, a primitive type, an array class, or 2298 * void. 2299 * 2300 * <p> See <em>The Java Language Specification</em>, section 8.2. 2301 * 2302 * @return the array of {@code Constructor} objects representing all the 2303 * declared constructors of this class 2304 * @throws SecurityException 2305 * If a security manager, <i>s</i>, is present and any of the 2306 * following conditions is met: 2307 * 2308 * <ul> 2309 * 2310 * <li> the caller's class loader is not the same as the 2311 * class loader of this class and invocation of 2312 * {@link SecurityManager#checkPermission 2313 * s.checkPermission} method with 2314 * {@code RuntimePermission("accessDeclaredMembers")} 2315 * denies access to the declared constructors within this class 2316 * 2317 * <li> the caller's class loader is not the same as or an 2318 * ancestor of the class loader for the current class and 2319 * invocation of {@link SecurityManager#checkPackageAccess 2320 * s.checkPackageAccess()} denies access to the package 2321 * of this class 2322 * 2323 * </ul> 2324 * 2325 * @since 1.1 2326 */ 2327 @CallerSensitive 2328 public Constructor<?>[] getDeclaredConstructors() throws SecurityException { 2329 SecurityManager sm = System.getSecurityManager(); 2330 if (sm != null) { 2331 checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true); 2332 } 2333 return copyConstructors(privateGetDeclaredConstructors(false)); 2334 } 2335 2336 2337 /** 2338 * Returns a {@code Field} object that reflects the specified declared 2339 * field of the class or interface represented by this {@code Class} 2340 * object. The {@code name} parameter is a {@code String} that specifies 2341 * the simple name of the desired field. 2342 * 2343 * <p> If this {@code Class} object represents an array type, then this 2344 * method does not find the {@code length} field of the array type. 2345 * 2346 * @param name the name of the field 2347 * @return the {@code Field} object for the specified field in this 2348 * class 2349 * @throws NoSuchFieldException if a field with the specified name is 2350 * not found. 2351 * @throws NullPointerException if {@code name} is {@code null} 2352 * @throws SecurityException 2353 * If a security manager, <i>s</i>, is present and any of the 2354 * following conditions is met: 2355 * 2356 * <ul> 2357 * 2358 * <li> the caller's class loader is not the same as the 2359 * class loader of this class and invocation of 2360 * {@link SecurityManager#checkPermission 2361 * s.checkPermission} method with 2362 * {@code RuntimePermission("accessDeclaredMembers")} 2363 * denies access to the declared field 2364 * 2365 * <li> the caller's class loader is not the same as or an 2366 * ancestor of the class loader for the current class and 2367 * invocation of {@link SecurityManager#checkPackageAccess 2368 * s.checkPackageAccess()} denies access to the package 2369 * of this class 2370 * 2371 * </ul> 2372 * 2373 * @since 1.1 2374 * @jls 8.2 Class Members 2375 * @jls 8.3 Field Declarations 2376 */ 2377 @CallerSensitive 2378 public Field getDeclaredField(String name) 2379 throws NoSuchFieldException, SecurityException { 2380 Objects.requireNonNull(name); 2381 SecurityManager sm = System.getSecurityManager(); 2382 if (sm != null) { 2383 checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true); 2384 } 2385 Field field = searchFields(privateGetDeclaredFields(false), name); 2386 if (field == null) { 2387 throw new NoSuchFieldException(name); 2388 } 2389 return getReflectionFactory().copyField(field); 2390 } 2391 2392 2393 /** 2394 * Returns a {@code Method} object that reflects the specified 2395 * declared method of the class or interface represented by this 2396 * {@code Class} object. The {@code name} parameter is a 2397 * {@code String} that specifies the simple name of the desired 2398 * method, and the {@code parameterTypes} parameter is an array of 2399 * {@code Class} objects that identify the method's formal parameter 2400 * types, in declared order. If more than one method with the same 2401 * parameter types is declared in a class, and one of these methods has a 2402 * return type that is more specific than any of the others, that method is 2403 * returned; otherwise one of the methods is chosen arbitrarily. If the 2404 * name is "<init>"or "<clinit>" a {@code NoSuchMethodException} 2405 * is raised. 2406 * 2407 * <p> If this {@code Class} object represents an array type, then this 2408 * method does not find the {@code clone()} method. 2409 * 2410 * @param name the name of the method 2411 * @param parameterTypes the parameter array 2412 * @return the {@code Method} object for the method of this class 2413 * matching the specified name and parameters 2414 * @throws NoSuchMethodException if a matching method is not found. 2415 * @throws NullPointerException if {@code name} is {@code null} 2416 * @throws SecurityException 2417 * If a security manager, <i>s</i>, is present and any of the 2418 * following conditions is met: 2419 * 2420 * <ul> 2421 * 2422 * <li> the caller's class loader is not the same as the 2423 * class loader of this class and invocation of 2424 * {@link SecurityManager#checkPermission 2425 * s.checkPermission} method with 2426 * {@code RuntimePermission("accessDeclaredMembers")} 2427 * denies access to the declared method 2428 * 2429 * <li> the caller's class loader is not the same as or an 2430 * ancestor of the class loader for the current class and 2431 * invocation of {@link SecurityManager#checkPackageAccess 2432 * s.checkPackageAccess()} denies access to the package 2433 * of this class 2434 * 2435 * </ul> 2436 * 2437 * @jls 8.2 Class Members 2438 * @jls 8.4 Method Declarations 2439 * @since 1.1 2440 */ 2441 @CallerSensitive 2442 public Method getDeclaredMethod(String name, Class<?>... parameterTypes) 2443 throws NoSuchMethodException, SecurityException { 2444 Objects.requireNonNull(name); 2445 SecurityManager sm = System.getSecurityManager(); 2446 if (sm != null) { 2447 checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true); 2448 } 2449 Method method = searchMethods(privateGetDeclaredMethods(false), name, parameterTypes); 2450 if (method == null) { 2451 throw new NoSuchMethodException(methodToString(name, parameterTypes)); 2452 } 2453 return getReflectionFactory().copyMethod(method); 2454 } 2455 2456 2457 /** 2458 * Returns a {@code Constructor} object that reflects the specified 2459 * constructor of the class or interface represented by this 2460 * {@code Class} object. The {@code parameterTypes} parameter is 2461 * an array of {@code Class} objects that identify the constructor's 2462 * formal parameter types, in declared order. 2463 * 2464 * If this {@code Class} object represents an inner class 2465 * declared in a non-static context, the formal parameter types 2466 * include the explicit enclosing instance as the first parameter. 2467 * 2468 * @param parameterTypes the parameter array 2469 * @return The {@code Constructor} object for the constructor with the 2470 * specified parameter list 2471 * @throws NoSuchMethodException if a matching method is not found. 2472 * @throws SecurityException 2473 * If a security manager, <i>s</i>, is present and any of the 2474 * following conditions is met: 2475 * 2476 * <ul> 2477 * 2478 * <li> the caller's class loader is not the same as the 2479 * class loader of this class and invocation of 2480 * {@link SecurityManager#checkPermission 2481 * s.checkPermission} method with 2482 * {@code RuntimePermission("accessDeclaredMembers")} 2483 * denies access to the declared constructor 2484 * 2485 * <li> the caller's class loader is not the same as or an 2486 * ancestor of the class loader for the current class and 2487 * invocation of {@link SecurityManager#checkPackageAccess 2488 * s.checkPackageAccess()} denies access to the package 2489 * of this class 2490 * 2491 * </ul> 2492 * 2493 * @since 1.1 2494 */ 2495 @CallerSensitive 2496 public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes) 2497 throws NoSuchMethodException, SecurityException 2498 { 2499 SecurityManager sm = System.getSecurityManager(); 2500 if (sm != null) { 2501 checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true); 2502 } 2503 2504 return getReflectionFactory().copyConstructor( 2505 getConstructor0(parameterTypes, Member.DECLARED)); 2506 } 2507 2508 /** 2509 * Finds a resource with a given name. 2510 * 2511 * <p> If this class is in a named {@link Module Module} then this method 2512 * will attempt to find the resource in the module. This is done by 2513 * delegating to the module's class loader {@link 2514 * ClassLoader#findResource(String,String) findResource(String,String)} 2515 * method, invoking it with the module name and the absolute name of the 2516 * resource. Resources in named modules are subject to the rules for 2517 * encapsulation specified in the {@code Module} {@link 2518 * Module#getResourceAsStream getResourceAsStream} method and so this 2519 * method returns {@code null} when the resource is a 2520 * non-"{@code .class}" resource in a package that is not open to the 2521 * caller's module. 2522 * 2523 * <p> Otherwise, if this class is not in a named module then the rules for 2524 * searching resources associated with a given class are implemented by the 2525 * defining {@linkplain ClassLoader class loader} of the class. This method 2526 * delegates to this object's class loader. If this object was loaded by 2527 * the bootstrap class loader, the method delegates to {@link 2528 * ClassLoader#getSystemResourceAsStream}. 2529 * 2530 * <p> Before delegation, an absolute resource name is constructed from the 2531 * given resource name using this algorithm: 2532 * 2533 * <ul> 2534 * 2535 * <li> If the {@code name} begins with a {@code '/'} 2536 * (<code>'\u002f'</code>), then the absolute name of the resource is the 2537 * portion of the {@code name} following the {@code '/'}. 2538 * 2539 * <li> Otherwise, the absolute name is of the following form: 2540 * 2541 * <blockquote> 2542 * {@code modified_package_name/name} 2543 * </blockquote> 2544 * 2545 * <p> Where the {@code modified_package_name} is the package name of this 2546 * object with {@code '/'} substituted for {@code '.'} 2547 * (<code>'\u002e'</code>). 2548 * 2549 * </ul> 2550 * 2551 * @param name name of the desired resource 2552 * @return A {@link java.io.InputStream} object; {@code null} if no 2553 * resource with this name is found, the resource is in a package 2554 * that is not {@link Module#isOpen(String, Module) open} to at 2555 * least the caller module, or access to the resource is denied 2556 * by the security manager. 2557 * @throws NullPointerException If {@code name} is {@code null} 2558 * 2559 * @see Module#getResourceAsStream(String) 2560 * @since 1.1 2561 * @revised 9 2562 * @spec JPMS 2563 */ 2564 @CallerSensitive 2565 public InputStream getResourceAsStream(String name) { 2566 name = resolveName(name); 2567 2568 Module thisModule = getModule(); 2569 if (thisModule.isNamed()) { 2570 // check if resource can be located by caller 2571 if (Resources.canEncapsulate(name) 2572 && !isOpenToCaller(name, Reflection.getCallerClass())) { 2573 return null; 2574 } 2575 2576 // resource not encapsulated or in package open to caller 2577 String mn = thisModule.getName(); 2578 ClassLoader cl = getClassLoader0(); 2579 try { 2580 2581 // special-case built-in class loaders to avoid the 2582 // need for a URL connection 2583 if (cl == null) { 2584 return BootLoader.findResourceAsStream(mn, name); 2585 } else if (cl instanceof BuiltinClassLoader) { 2586 return ((BuiltinClassLoader) cl).findResourceAsStream(mn, name); 2587 } else { 2588 URL url = cl.findResource(mn, name); 2589 return (url != null) ? url.openStream() : null; 2590 } 2591 2592 } catch (IOException | SecurityException e) { 2593 return null; 2594 } 2595 } 2596 2597 // unnamed module 2598 ClassLoader cl = getClassLoader0(); 2599 if (cl == null) { 2600 return ClassLoader.getSystemResourceAsStream(name); 2601 } else { 2602 return cl.getResourceAsStream(name); 2603 } 2604 } 2605 2606 /** 2607 * Finds a resource with a given name. 2608 * 2609 * <p> If this class is in a named {@link Module Module} then this method 2610 * will attempt to find the resource in the module. This is done by 2611 * delegating to the module's class loader {@link 2612 * ClassLoader#findResource(String,String) findResource(String,String)} 2613 * method, invoking it with the module name and the absolute name of the 2614 * resource. Resources in named modules are subject to the rules for 2615 * encapsulation specified in the {@code Module} {@link 2616 * Module#getResourceAsStream getResourceAsStream} method and so this 2617 * method returns {@code null} when the resource is a 2618 * non-"{@code .class}" resource in a package that is not open to the 2619 * caller's module. 2620 * 2621 * <p> Otherwise, if this class is not in a named module then the rules for 2622 * searching resources associated with a given class are implemented by the 2623 * defining {@linkplain ClassLoader class loader} of the class. This method 2624 * delegates to this object's class loader. If this object was loaded by 2625 * the bootstrap class loader, the method delegates to {@link 2626 * ClassLoader#getSystemResource}. 2627 * 2628 * <p> Before delegation, an absolute resource name is constructed from the 2629 * given resource name using this algorithm: 2630 * 2631 * <ul> 2632 * 2633 * <li> If the {@code name} begins with a {@code '/'} 2634 * (<code>'\u002f'</code>), then the absolute name of the resource is the 2635 * portion of the {@code name} following the {@code '/'}. 2636 * 2637 * <li> Otherwise, the absolute name is of the following form: 2638 * 2639 * <blockquote> 2640 * {@code modified_package_name/name} 2641 * </blockquote> 2642 * 2643 * <p> Where the {@code modified_package_name} is the package name of this 2644 * object with {@code '/'} substituted for {@code '.'} 2645 * (<code>'\u002e'</code>). 2646 * 2647 * </ul> 2648 * 2649 * @param name name of the desired resource 2650 * @return A {@link java.net.URL} object; {@code null} if no resource with 2651 * this name is found, the resource cannot be located by a URL, the 2652 * resource is in a package that is not 2653 * {@link Module#isOpen(String, Module) open} to at least the caller 2654 * module, or access to the resource is denied by the security 2655 * manager. 2656 * @throws NullPointerException If {@code name} is {@code null} 2657 * @since 1.1 2658 * @revised 9 2659 * @spec JPMS 2660 */ 2661 @CallerSensitive 2662 public URL getResource(String name) { 2663 name = resolveName(name); 2664 2665 Module thisModule = getModule(); 2666 if (thisModule.isNamed()) { 2667 // check if resource can be located by caller 2668 if (Resources.canEncapsulate(name) 2669 && !isOpenToCaller(name, Reflection.getCallerClass())) { 2670 return null; 2671 } 2672 2673 // resource not encapsulated or in package open to caller 2674 String mn = thisModule.getName(); 2675 ClassLoader cl = getClassLoader0(); 2676 try { 2677 if (cl == null) { 2678 return BootLoader.findResource(mn, name); 2679 } else { 2680 return cl.findResource(mn, name); 2681 } 2682 } catch (IOException ioe) { 2683 return null; 2684 } 2685 } 2686 2687 // unnamed module 2688 ClassLoader cl = getClassLoader0(); 2689 if (cl == null) { 2690 return ClassLoader.getSystemResource(name); 2691 } else { 2692 return cl.getResource(name); 2693 } 2694 } 2695 2696 /** 2697 * Returns true if a resource with the given name can be located by the 2698 * given caller. All resources in a module can be located by code in 2699 * the module. For other callers, then the package needs to be open to 2700 * the caller. 2701 */ 2702 private boolean isOpenToCaller(String name, Class<?> caller) { 2703 // assert getModule().isNamed(); 2704 Module thisModule = getModule(); 2705 Module callerModule = (caller != null) ? caller.getModule() : null; 2706 if (callerModule != thisModule) { 2707 String pn = Resources.toPackageName(name); 2708 if (thisModule.getDescriptor().packages().contains(pn)) { 2709 if (callerModule == null && !thisModule.isOpen(pn)) { 2710 // no caller, package not open 2711 return false; 2712 } 2713 if (!thisModule.isOpen(pn, callerModule)) { 2714 // package not open to caller 2715 return false; 2716 } 2717 } 2718 } 2719 return true; 2720 } 2721 2722 2723 /** protection domain returned when the internal domain is null */ 2724 private static java.security.ProtectionDomain allPermDomain; 2725 2726 /** 2727 * Returns the {@code ProtectionDomain} of this class. If there is a 2728 * security manager installed, this method first calls the security 2729 * manager's {@code checkPermission} method with a 2730 * {@code RuntimePermission("getProtectionDomain")} permission to 2731 * ensure it's ok to get the 2732 * {@code ProtectionDomain}. 2733 * 2734 * @return the ProtectionDomain of this class 2735 * 2736 * @throws SecurityException 2737 * if a security manager exists and its 2738 * {@code checkPermission} method doesn't allow 2739 * getting the ProtectionDomain. 2740 * 2741 * @see java.security.ProtectionDomain 2742 * @see SecurityManager#checkPermission 2743 * @see java.lang.RuntimePermission 2744 * @since 1.2 2745 */ 2746 public java.security.ProtectionDomain getProtectionDomain() { 2747 SecurityManager sm = System.getSecurityManager(); 2748 if (sm != null) { 2749 sm.checkPermission(SecurityConstants.GET_PD_PERMISSION); 2750 } 2751 java.security.ProtectionDomain pd = getProtectionDomain0(); 2752 if (pd == null) { 2753 if (allPermDomain == null) { 2754 java.security.Permissions perms = 2755 new java.security.Permissions(); 2756 perms.add(SecurityConstants.ALL_PERMISSION); 2757 allPermDomain = 2758 new java.security.ProtectionDomain(null, perms); 2759 } 2760 pd = allPermDomain; 2761 } 2762 return pd; 2763 } 2764 2765 2766 /** 2767 * Returns the ProtectionDomain of this class. 2768 */ 2769 private native java.security.ProtectionDomain getProtectionDomain0(); 2770 2771 /* 2772 * Return the Virtual Machine's Class object for the named 2773 * primitive type. 2774 */ 2775 static native Class<?> getPrimitiveClass(String name); 2776 2777 /* 2778 * Check if client is allowed to access members. If access is denied, 2779 * throw a SecurityException. 2780 * 2781 * This method also enforces package access. 2782 * 2783 * <p> Default policy: allow all clients access with normal Java access 2784 * control. 2785 * 2786 * <p> NOTE: should only be called if a SecurityManager is installed 2787 */ 2788 private void checkMemberAccess(SecurityManager sm, int which, 2789 Class<?> caller, boolean checkProxyInterfaces) { 2790 /* Default policy allows access to all {@link Member#PUBLIC} members, 2791 * as well as access to classes that have the same class loader as the caller. 2792 * In all other cases, it requires RuntimePermission("accessDeclaredMembers") 2793 * permission. 2794 */ 2795 final ClassLoader ccl = ClassLoader.getClassLoader(caller); 2796 if (which != Member.PUBLIC) { 2797 final ClassLoader cl = getClassLoader0(); 2798 if (ccl != cl) { 2799 sm.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION); 2800 } 2801 } 2802 this.checkPackageAccess(sm, ccl, checkProxyInterfaces); 2803 } 2804 2805 /* 2806 * Checks if a client loaded in ClassLoader ccl is allowed to access this 2807 * class under the current package access policy. If access is denied, 2808 * throw a SecurityException. 2809 * 2810 * NOTE: this method should only be called if a SecurityManager is active 2811 */ 2812 private void checkPackageAccess(SecurityManager sm, final ClassLoader ccl, 2813 boolean checkProxyInterfaces) { 2814 final ClassLoader cl = getClassLoader0(); 2815 2816 if (ReflectUtil.needsPackageAccessCheck(ccl, cl)) { 2817 String pkg = this.getPackageName(); 2818 if (pkg != null && !pkg.isEmpty()) { 2819 // skip the package access check on a proxy class in default proxy package 2820 if (!Proxy.isProxyClass(this) || ReflectUtil.isNonPublicProxyClass(this)) { 2821 sm.checkPackageAccess(pkg); 2822 } 2823 } 2824 } 2825 // check package access on the proxy interfaces 2826 if (checkProxyInterfaces && Proxy.isProxyClass(this)) { 2827 ReflectUtil.checkProxyPackageAccess(ccl, this.getInterfaces()); 2828 } 2829 } 2830 2831 /** 2832 * Add a package name prefix if the name is not absolute Remove leading "/" 2833 * if name is absolute 2834 */ 2835 private String resolveName(String name) { 2836 if (!name.startsWith("/")) { 2837 Class<?> c = this; 2838 while (c.isArray()) { 2839 c = c.getComponentType(); 2840 } 2841 String baseName = c.getPackageName(); 2842 if (baseName != null && !baseName.isEmpty()) { 2843 name = baseName.replace('.', '/') + "/" + name; 2844 } 2845 } else { 2846 name = name.substring(1); 2847 } 2848 return name; 2849 } 2850 2851 /** 2852 * Atomic operations support. 2853 */ 2854 private static class Atomic { 2855 // initialize Unsafe machinery here, since we need to call Class.class instance method 2856 // and have to avoid calling it in the static initializer of the Class class... 2857 private static final Unsafe unsafe = Unsafe.getUnsafe(); 2858 // offset of Class.reflectionData instance field 2859 private static final long reflectionDataOffset; 2860 // offset of Class.annotationType instance field 2861 private static final long annotationTypeOffset; 2862 // offset of Class.annotationData instance field 2863 private static final long annotationDataOffset; 2864 2865 static { 2866 reflectionDataOffset = objectFieldOffset("reflectionData"); 2867 annotationTypeOffset = objectFieldOffset("annotationType"); 2868 annotationDataOffset = objectFieldOffset("annotationData"); 2869 } 2870 2871 private static long objectFieldOffset(String fieldName) { 2872 return unsafe.objectFieldOffset(Class.class, fieldName); 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 }