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