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