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