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