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