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