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