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 new EnclosingMethodInfo(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 validate(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 EnclosingMethodInfo(Object[] enclosingInfo) { 1308 validate(enclosingInfo); 1309 this.enclosingClass = (Class<?>)enclosingInfo[0]; 1310 this.name = (String)enclosingInfo[1]; 1311 this.descriptor = (String)enclosingInfo[2]; 1312 } 1313 1314 boolean isPartial() { 1315 return enclosingClass == null || name == null || descriptor == null; 1316 } 1317 1318 boolean isConstructor() { return !isPartial() && "<init>".equals(name); } 1319 1320 boolean isMethod() { return !isPartial() && !isConstructor() && !"<clinit>".equals(name); } 1321 1322 Class<?> getEnclosingClass() { return enclosingClass; } 1323 1324 String getName() { return name; } 1325 1326 String getDescriptor() { return descriptor; } 1327 1328 } 1329 1330 private static Class<?> toClass(Type o) { 1331 if (o instanceof GenericArrayType) 1332 return Array.newInstance(toClass(((GenericArrayType)o).getGenericComponentType()), 1333 0) 1334 .getClass(); 1335 return (Class<?>)o; 1336 } 1337 1338 /** 1339 * If this {@code Class} object represents a local or anonymous 1340 * class within a constructor, returns a {@link 1341 * java.lang.reflect.Constructor Constructor} object representing 1342 * the immediately enclosing constructor of the underlying 1343 * class. Returns {@code null} otherwise. In particular, this 1344 * method returns {@code null} if the underlying class is a local 1345 * or anonymous class immediately enclosed by a type declaration, 1346 * instance initializer or static initializer. 1347 * 1348 * @return the immediately enclosing constructor of the underlying class, if 1349 * that class is a local or anonymous class; otherwise {@code null}. 1350 * @throws SecurityException 1351 * If a security manager, <i>s</i>, is present and any of the 1352 * following conditions is met: 1353 * 1354 * <ul> 1355 * 1356 * <li> the caller's class loader is not the same as the 1357 * class loader of the enclosing class and invocation of 1358 * {@link SecurityManager#checkPermission 1359 * s.checkPermission} method with 1360 * {@code RuntimePermission("accessDeclaredMembers")} 1361 * denies access to the constructors within the enclosing class 1362 * 1363 * <li> the caller's class loader is not the same as or an 1364 * ancestor of the class loader for the enclosing class and 1365 * invocation of {@link SecurityManager#checkPackageAccess 1366 * s.checkPackageAccess()} denies access to the package 1367 * of the enclosing class 1368 * 1369 * </ul> 1370 * @since 1.5 1371 */ 1372 @CallerSensitive 1373 public Constructor<?> getEnclosingConstructor() throws SecurityException { 1374 EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo(); 1375 1376 if (enclosingInfo == null) 1377 return null; 1378 else { 1379 if (!enclosingInfo.isConstructor()) 1380 return null; 1381 1382 ConstructorRepository typeInfo = ConstructorRepository.make(enclosingInfo.getDescriptor(), 1383 getFactory()); 1384 Type [] parameterTypes = typeInfo.getParameterTypes(); 1385 Class<?>[] parameterClasses = new Class<?>[parameterTypes.length]; 1386 1387 // Convert Types to Classes; returned types *should* 1388 // be class objects since the methodDescriptor's used 1389 // don't have generics information 1390 for(int i = 0; i < parameterClasses.length; i++) 1391 parameterClasses[i] = toClass(parameterTypes[i]); 1392 1393 // Perform access check 1394 final Class<?> enclosingCandidate = enclosingInfo.getEnclosingClass(); 1395 enclosingCandidate.checkMemberAccess(Member.DECLARED, 1396 Reflection.getCallerClass(), true); 1397 // Client is ok to access declared methods but j.l.Class might not be. 1398 Constructor<?>[] candidates = AccessController.doPrivileged( 1399 new PrivilegedAction<>() { 1400 @Override 1401 public Constructor<?>[] run() { 1402 return enclosingCandidate.getDeclaredConstructors(); 1403 } 1404 }); 1405 /* 1406 * Loop over all declared constructors; match number 1407 * of and type of parameters. 1408 */ 1409 for(Constructor<?> c: candidates) { 1410 Class<?>[] candidateParamClasses = c.getParameterTypes(); 1411 if (candidateParamClasses.length == parameterClasses.length) { 1412 boolean matches = true; 1413 for(int i = 0; i < candidateParamClasses.length; i++) { 1414 if (!candidateParamClasses[i].equals(parameterClasses[i])) { 1415 matches = false; 1416 break; 1417 } 1418 } 1419 1420 if (matches) 1421 return c; 1422 } 1423 } 1424 1425 throw new InternalError("Enclosing constructor not found"); 1426 } 1427 } 1428 1429 1430 /** 1431 * If the class or interface represented by this {@code Class} object 1432 * is a member of another class, returns the {@code Class} object 1433 * representing the class in which it was declared. This method returns 1434 * null if this class or interface is not a member of any other class. If 1435 * this {@code Class} object represents an array class, a primitive 1436 * type, or void,then this method returns null. 1437 * 1438 * @return the declaring class for this class 1439 * @throws SecurityException 1440 * If a security manager, <i>s</i>, is present and the caller's 1441 * class loader is not the same as or an ancestor of the class 1442 * loader for the declaring class and invocation of {@link 1443 * SecurityManager#checkPackageAccess s.checkPackageAccess()} 1444 * denies access to the package of the declaring class 1445 * @since 1.1 1446 */ 1447 @CallerSensitive 1448 public Class<?> getDeclaringClass() throws SecurityException { 1449 final Class<?> candidate = getDeclaringClass0(); 1450 1451 if (candidate != null) 1452 candidate.checkPackageAccess( 1453 ClassLoader.getClassLoader(Reflection.getCallerClass()), true); 1454 return candidate; 1455 } 1456 1457 private native Class<?> getDeclaringClass0(); 1458 1459 1460 /** 1461 * Returns the immediately enclosing class of the underlying 1462 * class. If the underlying class is a top level class this 1463 * method returns {@code null}. 1464 * @return the immediately enclosing class of the underlying class 1465 * @exception SecurityException 1466 * If a security manager, <i>s</i>, is present and the caller's 1467 * class loader is not the same as or an ancestor of the class 1468 * loader for the enclosing class and invocation of {@link 1469 * SecurityManager#checkPackageAccess s.checkPackageAccess()} 1470 * denies access to the package of the enclosing class 1471 * @since 1.5 1472 */ 1473 @CallerSensitive 1474 public Class<?> getEnclosingClass() throws SecurityException { 1475 // There are five kinds of classes (or interfaces): 1476 // a) Top level classes 1477 // b) Nested classes (static member classes) 1478 // c) Inner classes (non-static member classes) 1479 // d) Local classes (named classes declared within a method) 1480 // e) Anonymous classes 1481 1482 1483 // JVM Spec 4.7.7: A class must have an EnclosingMethod 1484 // attribute if and only if it is a local class or an 1485 // anonymous class. 1486 EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo(); 1487 Class<?> enclosingCandidate; 1488 1489 if (enclosingInfo == null) { 1490 // This is a top level or a nested class or an inner class (a, b, or c) 1491 enclosingCandidate = getDeclaringClass0(); 1492 } else { 1493 Class<?> enclosingClass = enclosingInfo.getEnclosingClass(); 1494 // This is a local class or an anonymous class (d or e) 1495 if (enclosingClass == this || enclosingClass == null) 1496 throw new InternalError("Malformed enclosing method information"); 1497 else 1498 enclosingCandidate = enclosingClass; 1499 } 1500 1501 if (enclosingCandidate != null) 1502 enclosingCandidate.checkPackageAccess( 1503 ClassLoader.getClassLoader(Reflection.getCallerClass()), true); 1504 return enclosingCandidate; 1505 } 1506 1507 /** 1508 * Returns the simple name of the underlying class as given in the 1509 * source code. Returns an empty string if the underlying class is 1510 * anonymous. 1511 * 1512 * <p>The simple name of an array is the simple name of the 1513 * component type with "[]" appended. In particular the simple 1514 * name of an array whose component type is anonymous is "[]". 1515 * 1516 * @return the simple name of the underlying class 1517 * @since 1.5 1518 */ 1519 public String getSimpleName() { 1520 if (isArray()) 1521 return getComponentType().getSimpleName()+"[]"; 1522 1523 String simpleName = getSimpleBinaryName(); 1524 if (simpleName == null) { // top level class 1525 simpleName = getName(); 1526 return simpleName.substring(simpleName.lastIndexOf('.')+1); // strip the package name 1527 } 1528 return simpleName; 1529 } 1530 1531 /** 1532 * Return an informative string for the name of this type. 1533 * 1534 * @return an informative string for the name of this type 1535 * @since 1.8 1536 */ 1537 public String getTypeName() { 1538 if (isArray()) { 1539 try { 1540 Class<?> cl = this; 1541 int dimensions = 0; 1542 while (cl.isArray()) { 1543 dimensions++; 1544 cl = cl.getComponentType(); 1545 } 1546 StringBuilder sb = new StringBuilder(); 1547 sb.append(cl.getName()); 1548 for (int i = 0; i < dimensions; i++) { 1549 sb.append("[]"); 1550 } 1551 return sb.toString(); 1552 } catch (Throwable e) { /*FALLTHRU*/ } 1553 } 1554 return getName(); 1555 } 1556 1557 /** 1558 * Returns the canonical name of the underlying class as 1559 * defined by the Java Language Specification. Returns null if 1560 * the underlying class does not have a canonical name (i.e., if 1561 * it is a local or anonymous class or an array whose component 1562 * type does not have a canonical name). 1563 * @return the canonical name of the underlying class if it exists, and 1564 * {@code null} otherwise. 1565 * @since 1.5 1566 */ 1567 public String getCanonicalName() { 1568 if (isArray()) { 1569 String canonicalName = getComponentType().getCanonicalName(); 1570 if (canonicalName != null) 1571 return canonicalName + "[]"; 1572 else 1573 return null; 1574 } 1575 if (isLocalOrAnonymousClass()) 1576 return null; 1577 Class<?> enclosingClass = getEnclosingClass(); 1578 if (enclosingClass == null) { // top level class 1579 return getName(); 1580 } else { 1581 String enclosingName = enclosingClass.getCanonicalName(); 1582 if (enclosingName == null) 1583 return null; 1584 return enclosingName + "." + getSimpleName(); 1585 } 1586 } 1587 1588 /** 1589 * Returns {@code true} if and only if the underlying class 1590 * is an anonymous class. 1591 * 1592 * @return {@code true} if and only if this class is an anonymous class. 1593 * @since 1.5 1594 */ 1595 public boolean isAnonymousClass() { 1596 return !isArray() && isLocalOrAnonymousClass() && 1597 getSimpleBinaryName0() == null; 1598 } 1599 1600 /** 1601 * Returns {@code true} if and only if the underlying class 1602 * is a local class. 1603 * 1604 * @return {@code true} if and only if this class is a local class. 1605 * @since 1.5 1606 */ 1607 public boolean isLocalClass() { 1608 return isLocalOrAnonymousClass() && 1609 (isArray() || getSimpleBinaryName0() != null); 1610 } 1611 1612 /** 1613 * Returns {@code true} if and only if the underlying class 1614 * is a member class. 1615 * 1616 * @return {@code true} if and only if this class is a member class. 1617 * @since 1.5 1618 */ 1619 public boolean isMemberClass() { 1620 return !isLocalOrAnonymousClass() && getDeclaringClass0() != null; 1621 } 1622 1623 /** 1624 * Returns the "simple binary name" of the underlying class, i.e., 1625 * the binary name without the leading enclosing class name. 1626 * Returns {@code null} if the underlying class is a top level 1627 * class. 1628 */ 1629 private String getSimpleBinaryName() { 1630 if (isTopLevelClass()) 1631 return null; 1632 String name = getSimpleBinaryName0(); 1633 if (name == null) // anonymous class 1634 return ""; 1635 return name; 1636 } 1637 1638 private native String getSimpleBinaryName0(); 1639 1640 /** 1641 * Returns {@code true} if this is a top level class. Returns {@code false} 1642 * otherwise. 1643 */ 1644 private boolean isTopLevelClass() { 1645 return !isLocalOrAnonymousClass() && getDeclaringClass0() == null; 1646 } 1647 1648 /** 1649 * Returns {@code true} if this is a local class or an anonymous 1650 * class. Returns {@code false} otherwise. 1651 */ 1652 private boolean isLocalOrAnonymousClass() { 1653 // JVM Spec 4.7.7: A class must have an EnclosingMethod 1654 // attribute if and only if it is a local class or an 1655 // anonymous class. 1656 return hasEnclosingMethodInfo(); 1657 } 1658 1659 private boolean hasEnclosingMethodInfo() { 1660 Object[] enclosingInfo = getEnclosingMethod0(); 1661 if (enclosingInfo != null) { 1662 EnclosingMethodInfo.validate(enclosingInfo); 1663 return true; 1664 } 1665 return false; 1666 } 1667 1668 /** 1669 * Returns an array containing {@code Class} objects representing all 1670 * the public classes and interfaces that are members of the class 1671 * represented by this {@code Class} object. This includes public 1672 * class and interface members inherited from superclasses and public class 1673 * and interface members declared by the class. This method returns an 1674 * array of length 0 if this {@code Class} object has no public member 1675 * classes or interfaces. This method also returns an array of length 0 if 1676 * this {@code Class} object represents a primitive type, an array 1677 * class, or void. 1678 * 1679 * @return the array of {@code Class} objects representing the public 1680 * members of this class 1681 * @throws SecurityException 1682 * If a security manager, <i>s</i>, is present and 1683 * the caller's class loader is not the same as or an 1684 * ancestor of the class loader for the current class and 1685 * invocation of {@link SecurityManager#checkPackageAccess 1686 * s.checkPackageAccess()} denies access to the package 1687 * of this class. 1688 * 1689 * @since 1.1 1690 */ 1691 @CallerSensitive 1692 public Class<?>[] getClasses() { 1693 checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), false); 1694 1695 // Privileged so this implementation can look at DECLARED classes, 1696 // something the caller might not have privilege to do. The code here 1697 // is allowed to look at DECLARED classes because (1) it does not hand 1698 // out anything other than public members and (2) public member access 1699 // has already been ok'd by the SecurityManager. 1700 1701 return java.security.AccessController.doPrivileged( 1702 new java.security.PrivilegedAction<>() { 1703 public Class<?>[] run() { 1704 List<Class<?>> list = new ArrayList<>(); 1705 Class<?> currentClass = Class.this; 1706 while (currentClass != null) { 1707 for (Class<?> m : currentClass.getDeclaredClasses()) { 1708 if (Modifier.isPublic(m.getModifiers())) { 1709 list.add(m); 1710 } 1711 } 1712 currentClass = currentClass.getSuperclass(); 1713 } 1714 return list.toArray(new Class<?>[0]); 1715 } 1716 }); 1717 } 1718 1719 1720 /** 1721 * Returns an array containing {@code Field} objects reflecting all 1722 * the accessible public fields of the class or interface represented by 1723 * this {@code Class} object. 1724 * 1725 * <p> If this {@code Class} object represents a class or interface with 1726 * no accessible public fields, then this method returns an array of length 1727 * 0. 1728 * 1729 * <p> If this {@code Class} object represents a class, then this method 1730 * returns the public fields of the class and of all its superclasses and 1731 * superinterfaces. 1732 * 1733 * <p> If this {@code Class} object represents an interface, then this 1734 * method returns the fields of the interface and of all its 1735 * superinterfaces. 1736 * 1737 * <p> If this {@code Class} object represents an array type, a primitive 1738 * type, or void, then this method returns an array of length 0. 1739 * 1740 * <p> The elements in the returned array are not sorted and are not in any 1741 * particular order. 1742 * 1743 * @return the array of {@code Field} objects representing the 1744 * public fields 1745 * @throws SecurityException 1746 * If a security manager, <i>s</i>, is present and 1747 * the caller's class loader is not the same as or an 1748 * ancestor of the class loader for the current class and 1749 * invocation of {@link SecurityManager#checkPackageAccess 1750 * s.checkPackageAccess()} denies access to the package 1751 * of this class. 1752 * 1753 * @since 1.1 1754 * @jls 8.2 Class Members 1755 * @jls 8.3 Field Declarations 1756 */ 1757 @CallerSensitive 1758 public Field[] getFields() throws SecurityException { 1759 checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true); 1760 return copyFields(privateGetPublicFields(null)); 1761 } 1762 1763 1764 /** 1765 * Returns an array containing {@code Method} objects reflecting all the 1766 * public methods of the class or interface represented by this {@code 1767 * Class} object, including those declared by the class or interface and 1768 * those inherited from superclasses and superinterfaces. 1769 * 1770 * <p> If this {@code Class} object represents a type that has multiple 1771 * public methods with the same name and parameter types, but different 1772 * return types, then the returned array has a {@code Method} object for 1773 * each such method. 1774 * 1775 * <p> If this {@code Class} object represents a type with a class 1776 * initialization method {@code <clinit>}, then the returned array does 1777 * <em>not</em> have a corresponding {@code Method} object. 1778 * 1779 * <p> If this {@code Class} object represents an array type, then the 1780 * returned array has a {@code Method} object for each of the public 1781 * methods inherited by the array type from {@code Object}. It does not 1782 * contain a {@code Method} object for {@code clone()}. 1783 * 1784 * <p> If this {@code Class} object represents an interface then the 1785 * returned array does not contain any implicitly declared methods from 1786 * {@code Object}. Therefore, if no methods are explicitly declared in 1787 * this interface or any of its superinterfaces then the returned array 1788 * has length 0. (Note that a {@code Class} object which represents a class 1789 * always has public methods, inherited from {@code Object}.) 1790 * 1791 * <p> If this {@code Class} object represents a primitive type or void, 1792 * then the returned array has length 0. 1793 * 1794 * <p> Static methods declared in superinterfaces of the class or interface 1795 * represented by this {@code Class} object are not considered members of 1796 * the class or interface. 1797 * 1798 * <p> The elements in the returned array are not sorted and are not in any 1799 * particular order. 1800 * 1801 * @return the array of {@code Method} objects representing the 1802 * public methods of this class 1803 * @throws SecurityException 1804 * If a security manager, <i>s</i>, is present and 1805 * the caller's class loader is not the same as or an 1806 * ancestor of the class loader for the current class and 1807 * invocation of {@link SecurityManager#checkPackageAccess 1808 * s.checkPackageAccess()} denies access to the package 1809 * of this class. 1810 * 1811 * @jls 8.2 Class Members 1812 * @jls 8.4 Method Declarations 1813 * @since 1.1 1814 */ 1815 @CallerSensitive 1816 public Method[] getMethods() throws SecurityException { 1817 checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true); 1818 return copyMethods(privateGetPublicMethods()); 1819 } 1820 1821 1822 /** 1823 * Returns an array containing {@code Constructor} objects reflecting 1824 * all the public constructors of the class represented by this 1825 * {@code Class} object. An array of length 0 is returned if the 1826 * class has no public constructors, or if the class is an array class, or 1827 * if the class reflects a primitive type or void. 1828 * 1829 * Note that while this method returns an array of {@code 1830 * Constructor<T>} objects (that is an array of constructors from 1831 * this class), the return type of this method is {@code 1832 * Constructor<?>[]} and <em>not</em> {@code Constructor<T>[]} as 1833 * might be expected. This less informative return type is 1834 * necessary since after being returned from this method, the 1835 * array could be modified to hold {@code Constructor} objects for 1836 * different classes, which would violate the type guarantees of 1837 * {@code Constructor<T>[]}. 1838 * 1839 * @return the array of {@code Constructor} objects representing the 1840 * public constructors of this class 1841 * @throws SecurityException 1842 * If a security manager, <i>s</i>, is present and 1843 * the caller's class loader is not the same as or an 1844 * ancestor of the class loader for the current class and 1845 * invocation of {@link SecurityManager#checkPackageAccess 1846 * s.checkPackageAccess()} denies access to the package 1847 * of this class. 1848 * 1849 * @since 1.1 1850 */ 1851 @CallerSensitive 1852 public Constructor<?>[] getConstructors() throws SecurityException { 1853 checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true); 1854 return copyConstructors(privateGetDeclaredConstructors(true)); 1855 } 1856 1857 1858 /** 1859 * Returns a {@code Field} object that reflects the specified public member 1860 * field of the class or interface represented by this {@code Class} 1861 * object. The {@code name} parameter is a {@code String} specifying the 1862 * simple name of the desired field. 1863 * 1864 * <p> The field to be reflected is determined by the algorithm that 1865 * follows. Let C be the class or interface represented by this object: 1866 * 1867 * <OL> 1868 * <LI> If C declares a public field with the name specified, that is the 1869 * field to be reflected.</LI> 1870 * <LI> If no field was found in step 1 above, this algorithm is applied 1871 * recursively to each direct superinterface of C. The direct 1872 * superinterfaces are searched in the order they were declared.</LI> 1873 * <LI> If no field was found in steps 1 and 2 above, and C has a 1874 * superclass S, then this algorithm is invoked recursively upon S. 1875 * If C has no superclass, then a {@code NoSuchFieldException} 1876 * is thrown.</LI> 1877 * </OL> 1878 * 1879 * <p> If this {@code Class} object represents an array type, then this 1880 * method does not find the {@code length} field of the array type. 1881 * 1882 * @param name the field name 1883 * @return the {@code Field} object of this class specified by 1884 * {@code name} 1885 * @throws NoSuchFieldException if a field with the specified name is 1886 * not found. 1887 * @throws NullPointerException if {@code name} is {@code null} 1888 * @throws SecurityException 1889 * If a security manager, <i>s</i>, is present and 1890 * the caller's class loader is not the same as or an 1891 * ancestor of the class loader for the current class and 1892 * invocation of {@link SecurityManager#checkPackageAccess 1893 * s.checkPackageAccess()} denies access to the package 1894 * of this class. 1895 * 1896 * @since 1.1 1897 * @jls 8.2 Class Members 1898 * @jls 8.3 Field Declarations 1899 */ 1900 @CallerSensitive 1901 public Field getField(String name) 1902 throws NoSuchFieldException, SecurityException { 1903 checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true); 1904 Field field = getField0(name); 1905 if (field == null) { 1906 throw new NoSuchFieldException(name); 1907 } 1908 return field; 1909 } 1910 1911 1912 /** 1913 * Returns a {@code Method} object that reflects the specified public 1914 * member method of the class or interface represented by this 1915 * {@code Class} object. The {@code name} parameter is a 1916 * {@code String} specifying the simple name of the desired method. The 1917 * {@code parameterTypes} parameter is an array of {@code Class} 1918 * objects that identify the method's formal parameter types, in declared 1919 * order. If {@code parameterTypes} is {@code null}, it is 1920 * treated as if it were an empty array. 1921 * 1922 * <p> If the {@code name} is "{@code <init>}" or "{@code <clinit>}" a 1923 * {@code NoSuchMethodException} is raised. Otherwise, the method to 1924 * be reflected is determined by the algorithm that follows. Let C be the 1925 * class or interface represented by this object: 1926 * <OL> 1927 * <LI> C is searched for a <I>matching method</I>, as defined below. If a 1928 * matching method is found, it is reflected.</LI> 1929 * <LI> If no matching method is found by step 1 then: 1930 * <OL TYPE="a"> 1931 * <LI> If C is a class other than {@code Object}, then this algorithm is 1932 * invoked recursively on the superclass of C.</LI> 1933 * <LI> If C is the class {@code Object}, or if C is an interface, then 1934 * the superinterfaces of C (if any) are searched for a matching 1935 * method. If any such method is found, it is reflected.</LI> 1936 * </OL></LI> 1937 * </OL> 1938 * 1939 * <p> To find a matching method in a class or interface C: If C 1940 * declares exactly one public method with the specified name and exactly 1941 * the same formal parameter types, that is the method reflected. If more 1942 * than one such method is found in C, and one of these methods has a 1943 * return type that is more specific than any of the others, that method is 1944 * reflected; otherwise one of the methods is chosen arbitrarily. 1945 * 1946 * <p>Note that there may be more than one matching method in a 1947 * class because while the Java language forbids a class to 1948 * declare multiple methods with the same signature but different 1949 * return types, the Java virtual machine does not. This 1950 * increased flexibility in the virtual machine can be used to 1951 * implement various language features. For example, covariant 1952 * returns can be implemented with {@linkplain 1953 * java.lang.reflect.Method#isBridge bridge methods}; the bridge 1954 * method and the method being overridden would have the same 1955 * signature but different return types. 1956 * 1957 * <p> If this {@code Class} object represents an array type, then this 1958 * method does not find the {@code clone()} method. 1959 * 1960 * <p> Static methods declared in superinterfaces of the class or interface 1961 * represented by this {@code Class} object are not considered members of 1962 * the class or interface. 1963 * 1964 * @param name the name of the method 1965 * @param parameterTypes the list of parameters 1966 * @return the {@code Method} object that matches the specified 1967 * {@code name} and {@code parameterTypes} 1968 * @throws NoSuchMethodException if a matching method is not found 1969 * or if the name is "<init>"or "<clinit>". 1970 * @throws NullPointerException if {@code name} is {@code null} 1971 * @throws SecurityException 1972 * If a security manager, <i>s</i>, is present and 1973 * the caller's class loader is not the same as or an 1974 * ancestor of the class loader for the current class and 1975 * invocation of {@link SecurityManager#checkPackageAccess 1976 * s.checkPackageAccess()} denies access to the package 1977 * of this class. 1978 * 1979 * @jls 8.2 Class Members 1980 * @jls 8.4 Method Declarations 1981 * @since 1.1 1982 */ 1983 @CallerSensitive 1984 public Method getMethod(String name, Class<?>... parameterTypes) 1985 throws NoSuchMethodException, SecurityException { 1986 checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true); 1987 Method method = getMethod0(name, parameterTypes, true); 1988 if (method == null) { 1989 throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes)); 1990 } 1991 return method; 1992 } 1993 1994 /** 1995 * Returns a {@code Method} object that reflects the specified public 1996 * member method of the class or interface represented by this 1997 * {@code Class} object. 1998 * 1999 * @param name the name of the method 2000 * @param parameterTypes the list of parameters 2001 * @return the {@code Method} object that matches the specified 2002 * {@code name} and {@code parameterTypes}; {@code null} 2003 * if the method is not found or the name is 2004 * "<init>"or "<clinit>". 2005 */ 2006 Method getMethodOrNull(String name, Class<?>... parameterTypes) { 2007 return getMethod0(name, parameterTypes, true); 2008 } 2009 2010 2011 /** 2012 * Returns a {@code Constructor} object that reflects the specified 2013 * public constructor of the class represented by this {@code Class} 2014 * object. The {@code parameterTypes} parameter is an array of 2015 * {@code Class} objects that identify the constructor's formal 2016 * parameter types, in declared order. 2017 * 2018 * If this {@code Class} object represents an inner class 2019 * declared in a non-static context, the formal parameter types 2020 * include the explicit enclosing instance as the first parameter. 2021 * 2022 * <p> The constructor to reflect is the public constructor of the class 2023 * represented by this {@code Class} object whose formal parameter 2024 * types match those specified by {@code parameterTypes}. 2025 * 2026 * @param parameterTypes the parameter array 2027 * @return the {@code Constructor} object of the public constructor that 2028 * matches the specified {@code parameterTypes} 2029 * @throws NoSuchMethodException if a matching method is not found. 2030 * @throws SecurityException 2031 * If a security manager, <i>s</i>, is present and 2032 * the caller's class loader is not the same as or an 2033 * ancestor of the class loader for the current class and 2034 * invocation of {@link SecurityManager#checkPackageAccess 2035 * s.checkPackageAccess()} denies access to the package 2036 * of this class. 2037 * 2038 * @since 1.1 2039 */ 2040 @CallerSensitive 2041 public Constructor<T> getConstructor(Class<?>... parameterTypes) 2042 throws NoSuchMethodException, SecurityException { 2043 checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true); 2044 return getConstructor0(parameterTypes, Member.PUBLIC); 2045 } 2046 2047 2048 /** 2049 * Returns an array of {@code Class} objects reflecting all the 2050 * classes and interfaces declared as members of the class represented by 2051 * this {@code Class} object. This includes public, protected, default 2052 * (package) access, and private classes and interfaces declared by the 2053 * class, but excludes inherited classes and interfaces. This method 2054 * returns an array of length 0 if the class declares no classes or 2055 * interfaces as members, or if this {@code Class} object represents a 2056 * primitive type, an array class, or void. 2057 * 2058 * @return the array of {@code Class} objects representing all the 2059 * declared members of this class 2060 * @throws SecurityException 2061 * If a security manager, <i>s</i>, is present and any of the 2062 * following conditions is met: 2063 * 2064 * <ul> 2065 * 2066 * <li> the caller's class loader is not the same as the 2067 * class loader of this class and invocation of 2068 * {@link SecurityManager#checkPermission 2069 * s.checkPermission} method with 2070 * {@code RuntimePermission("accessDeclaredMembers")} 2071 * denies access to the declared classes within this class 2072 * 2073 * <li> the caller's class loader is not the same as or an 2074 * ancestor of the class loader for the current class and 2075 * invocation of {@link SecurityManager#checkPackageAccess 2076 * s.checkPackageAccess()} denies access to the package 2077 * of this class 2078 * 2079 * </ul> 2080 * 2081 * @since 1.1 2082 */ 2083 @CallerSensitive 2084 public Class<?>[] getDeclaredClasses() throws SecurityException { 2085 checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), false); 2086 return getDeclaredClasses0(); 2087 } 2088 2089 2090 /** 2091 * Returns an array of {@code Field} objects reflecting all the fields 2092 * declared by the class or interface represented by this 2093 * {@code Class} object. This includes public, protected, default 2094 * (package) access, and private fields, but excludes inherited fields. 2095 * 2096 * <p> If this {@code Class} object represents a class or interface with no 2097 * declared fields, then this method returns an array of length 0. 2098 * 2099 * <p> If this {@code Class} object represents an array type, a primitive 2100 * type, or void, then this method returns an array of length 0. 2101 * 2102 * <p> The elements in the returned array are not sorted and are not in any 2103 * particular order. 2104 * 2105 * @return the array of {@code Field} objects representing all the 2106 * declared fields of this class 2107 * @throws SecurityException 2108 * If a security manager, <i>s</i>, is present and any of the 2109 * following conditions is met: 2110 * 2111 * <ul> 2112 * 2113 * <li> the caller's class loader is not the same as the 2114 * class loader of this class and invocation of 2115 * {@link SecurityManager#checkPermission 2116 * s.checkPermission} method with 2117 * {@code RuntimePermission("accessDeclaredMembers")} 2118 * denies access to the declared fields within this class 2119 * 2120 * <li> the caller's class loader is not the same as or an 2121 * ancestor of the class loader for the current class and 2122 * invocation of {@link SecurityManager#checkPackageAccess 2123 * s.checkPackageAccess()} denies access to the package 2124 * of this class 2125 * 2126 * </ul> 2127 * 2128 * @since 1.1 2129 * @jls 8.2 Class Members 2130 * @jls 8.3 Field Declarations 2131 */ 2132 @CallerSensitive 2133 public Field[] getDeclaredFields() throws SecurityException { 2134 checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true); 2135 return copyFields(privateGetDeclaredFields(false)); 2136 } 2137 2138 2139 /** 2140 * 2141 * Returns an array containing {@code Method} objects reflecting all the 2142 * declared methods of the class or interface represented by this {@code 2143 * Class} object, including public, protected, default (package) 2144 * access, and private methods, but excluding inherited methods. 2145 * 2146 * <p> If this {@code Class} object represents a type that has multiple 2147 * declared methods with the same name and parameter types, but different 2148 * return types, then the returned array has a {@code Method} object for 2149 * each such method. 2150 * 2151 * <p> If this {@code Class} object represents a type that has a class 2152 * initialization method {@code <clinit>}, then the returned array does 2153 * <em>not</em> have a corresponding {@code Method} object. 2154 * 2155 * <p> If this {@code Class} object represents a class or interface with no 2156 * declared methods, then the returned array has length 0. 2157 * 2158 * <p> If this {@code Class} object represents an array type, a primitive 2159 * type, or void, then the returned array has length 0. 2160 * 2161 * <p> The elements in the returned array are not sorted and are not in any 2162 * particular order. 2163 * 2164 * @return the array of {@code Method} objects representing all the 2165 * declared methods of this class 2166 * @throws SecurityException 2167 * If a security manager, <i>s</i>, is present and any of the 2168 * following conditions is met: 2169 * 2170 * <ul> 2171 * 2172 * <li> the caller's class loader is not the same as the 2173 * class loader of this class and invocation of 2174 * {@link SecurityManager#checkPermission 2175 * s.checkPermission} method with 2176 * {@code RuntimePermission("accessDeclaredMembers")} 2177 * denies access to the declared methods within this class 2178 * 2179 * <li> the caller's class loader is not the same as or an 2180 * ancestor of the class loader for the current class and 2181 * invocation of {@link SecurityManager#checkPackageAccess 2182 * s.checkPackageAccess()} denies access to the package 2183 * of this class 2184 * 2185 * </ul> 2186 * 2187 * @jls 8.2 Class Members 2188 * @jls 8.4 Method Declarations 2189 * @since 1.1 2190 */ 2191 @CallerSensitive 2192 public Method[] getDeclaredMethods() throws SecurityException { 2193 checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true); 2194 return copyMethods(privateGetDeclaredMethods(false)); 2195 } 2196 2197 2198 /** 2199 * Returns an array of {@code Constructor} objects reflecting all the 2200 * constructors declared by the class represented by this 2201 * {@code Class} object. These are public, protected, default 2202 * (package) access, and private constructors. The elements in the array 2203 * returned are not sorted and are not in any particular order. If the 2204 * class has a default constructor, it is included in the returned array. 2205 * This method returns an array of length 0 if this {@code Class} 2206 * object represents an interface, a primitive type, an array class, or 2207 * void. 2208 * 2209 * <p> See <em>The Java Language Specification</em>, section 8.2. 2210 * 2211 * @return the array of {@code Constructor} objects representing all the 2212 * declared constructors of this class 2213 * @throws SecurityException 2214 * If a security manager, <i>s</i>, is present and any of the 2215 * following conditions is met: 2216 * 2217 * <ul> 2218 * 2219 * <li> the caller's class loader is not the same as the 2220 * class loader of this class and invocation of 2221 * {@link SecurityManager#checkPermission 2222 * s.checkPermission} method with 2223 * {@code RuntimePermission("accessDeclaredMembers")} 2224 * denies access to the declared constructors within this class 2225 * 2226 * <li> the caller's class loader is not the same as or an 2227 * ancestor of the class loader for the current class and 2228 * invocation of {@link SecurityManager#checkPackageAccess 2229 * s.checkPackageAccess()} denies access to the package 2230 * of this class 2231 * 2232 * </ul> 2233 * 2234 * @since 1.1 2235 */ 2236 @CallerSensitive 2237 public Constructor<?>[] getDeclaredConstructors() throws SecurityException { 2238 checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true); 2239 return copyConstructors(privateGetDeclaredConstructors(false)); 2240 } 2241 2242 2243 /** 2244 * Returns a {@code Field} object that reflects the specified declared 2245 * field of the class or interface represented by this {@code Class} 2246 * object. The {@code name} parameter is a {@code String} that specifies 2247 * the simple name of the desired field. 2248 * 2249 * <p> If this {@code Class} object represents an array type, then this 2250 * method does not find the {@code length} field of the array type. 2251 * 2252 * @param name the name of the field 2253 * @return the {@code Field} object for the specified field in this 2254 * class 2255 * @throws NoSuchFieldException if a field with the specified name is 2256 * not found. 2257 * @throws NullPointerException if {@code name} is {@code null} 2258 * @throws SecurityException 2259 * If a security manager, <i>s</i>, is present and any of the 2260 * following conditions is met: 2261 * 2262 * <ul> 2263 * 2264 * <li> the caller's class loader is not the same as the 2265 * class loader of this class and invocation of 2266 * {@link SecurityManager#checkPermission 2267 * s.checkPermission} method with 2268 * {@code RuntimePermission("accessDeclaredMembers")} 2269 * denies access to the declared field 2270 * 2271 * <li> the caller's class loader is not the same as or an 2272 * ancestor of the class loader for the current class and 2273 * invocation of {@link SecurityManager#checkPackageAccess 2274 * s.checkPackageAccess()} denies access to the package 2275 * of this class 2276 * 2277 * </ul> 2278 * 2279 * @since 1.1 2280 * @jls 8.2 Class Members 2281 * @jls 8.3 Field Declarations 2282 */ 2283 @CallerSensitive 2284 public Field getDeclaredField(String name) 2285 throws NoSuchFieldException, SecurityException { 2286 checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true); 2287 Field field = searchFields(privateGetDeclaredFields(false), name); 2288 if (field == null) { 2289 throw new NoSuchFieldException(name); 2290 } 2291 return field; 2292 } 2293 2294 2295 /** 2296 * Returns a {@code Method} object that reflects the specified 2297 * declared method of the class or interface represented by this 2298 * {@code Class} object. The {@code name} parameter is a 2299 * {@code String} that specifies the simple name of the desired 2300 * method, and the {@code parameterTypes} parameter is an array of 2301 * {@code Class} objects that identify the method's formal parameter 2302 * types, in declared order. If more than one method with the same 2303 * parameter types is declared in a class, and one of these methods has a 2304 * return type that is more specific than any of the others, that method is 2305 * returned; otherwise one of the methods is chosen arbitrarily. If the 2306 * name is "<init>"or "<clinit>" a {@code NoSuchMethodException} 2307 * is raised. 2308 * 2309 * <p> If this {@code Class} object represents an array type, then this 2310 * method does not find the {@code clone()} method. 2311 * 2312 * @param name the name of the method 2313 * @param parameterTypes the parameter array 2314 * @return the {@code Method} object for the method of this class 2315 * matching the specified name and parameters 2316 * @throws NoSuchMethodException if a matching method is not found. 2317 * @throws NullPointerException if {@code name} is {@code null} 2318 * @throws SecurityException 2319 * If a security manager, <i>s</i>, is present and any of the 2320 * following conditions is met: 2321 * 2322 * <ul> 2323 * 2324 * <li> the caller's class loader is not the same as the 2325 * class loader of this class and invocation of 2326 * {@link SecurityManager#checkPermission 2327 * s.checkPermission} method with 2328 * {@code RuntimePermission("accessDeclaredMembers")} 2329 * denies access to the declared method 2330 * 2331 * <li> the caller's class loader is not the same as or an 2332 * ancestor of the class loader for the current class and 2333 * invocation of {@link SecurityManager#checkPackageAccess 2334 * s.checkPackageAccess()} denies access to the package 2335 * of this class 2336 * 2337 * </ul> 2338 * 2339 * @jls 8.2 Class Members 2340 * @jls 8.4 Method Declarations 2341 * @since 1.1 2342 */ 2343 @CallerSensitive 2344 public Method getDeclaredMethod(String name, Class<?>... parameterTypes) 2345 throws NoSuchMethodException, SecurityException { 2346 checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true); 2347 Method method = searchMethods(privateGetDeclaredMethods(false), name, parameterTypes); 2348 if (method == null) { 2349 throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes)); 2350 } 2351 return method; 2352 } 2353 2354 2355 /** 2356 * Returns a {@code Constructor} object that reflects the specified 2357 * constructor of the class or interface represented by this 2358 * {@code Class} object. The {@code parameterTypes} parameter is 2359 * an array of {@code Class} objects that identify the constructor's 2360 * formal parameter types, in declared order. 2361 * 2362 * If this {@code Class} object represents an inner class 2363 * declared in a non-static context, the formal parameter types 2364 * include the explicit enclosing instance as the first parameter. 2365 * 2366 * @param parameterTypes the parameter array 2367 * @return The {@code Constructor} object for the constructor with the 2368 * specified parameter list 2369 * @throws NoSuchMethodException if a matching method is not found. 2370 * @throws SecurityException 2371 * If a security manager, <i>s</i>, is present and any of the 2372 * following conditions is met: 2373 * 2374 * <ul> 2375 * 2376 * <li> the caller's class loader is not the same as the 2377 * class loader of this class and invocation of 2378 * {@link SecurityManager#checkPermission 2379 * s.checkPermission} method with 2380 * {@code RuntimePermission("accessDeclaredMembers")} 2381 * denies access to the declared constructor 2382 * 2383 * <li> the caller's class loader is not the same as or an 2384 * ancestor of the class loader for the current class and 2385 * invocation of {@link SecurityManager#checkPackageAccess 2386 * s.checkPackageAccess()} denies access to the package 2387 * of this class 2388 * 2389 * </ul> 2390 * 2391 * @since 1.1 2392 */ 2393 @CallerSensitive 2394 public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes) 2395 throws NoSuchMethodException, SecurityException { 2396 checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true); 2397 return getConstructor0(parameterTypes, Member.DECLARED); 2398 } 2399 2400 /** 2401 * Finds a resource with a given name. 2402 * 2403 * <p> If this class is in a named {@link Module Module} then this method 2404 * will attempt to find the resource in the module by means of the absolute 2405 * resource name, subject to the rules for encapsulation specified in the 2406 * {@code Module} {@link Module#getResourceAsStream getResourceAsStream} 2407 * method. 2408 * 2409 * <p> Otherwise, if this class is not in a named module then the rules for 2410 * searching resources associated with a given class are implemented by the 2411 * defining {@linkplain ClassLoader class loader} of the class. This method 2412 * delegates to this object's class loader. If this object was loaded by 2413 * the bootstrap class loader, the method delegates to {@link 2414 * ClassLoader#getSystemResourceAsStream}. 2415 * 2416 * <p> Before finding a resource in the caller's module or delegation to a 2417 * class loader, an absolute resource name is constructed from the given 2418 * resource name using this algorithm: 2419 * 2420 * <ul> 2421 * 2422 * <li> If the {@code name} begins with a {@code '/'} 2423 * (<tt>'\u002f'</tt>), then the absolute name of the resource is the 2424 * portion of the {@code name} following the {@code '/'}. 2425 * 2426 * <li> Otherwise, the absolute name is of the following form: 2427 * 2428 * <blockquote> 2429 * {@code modified_package_name/name} 2430 * </blockquote> 2431 * 2432 * <p> Where the {@code modified_package_name} is the package name of this 2433 * object with {@code '/'} substituted for {@code '.'} 2434 * (<tt>'\u002e'</tt>). 2435 * 2436 * </ul> 2437 * 2438 * @param name name of the desired resource 2439 * @return A {@link java.io.InputStream} object; {@code null} if no 2440 * resource with this name is found, the resource is in a package 2441 * that is not {@link Module#isOpen(String, Module) open} to at 2442 * least the caller module, or access to the resource is denied 2443 * by the security manager. 2444 * @throws NullPointerException If {@code name} is {@code null} 2445 * @since 1.1 2446 */ 2447 @CallerSensitive 2448 public InputStream getResourceAsStream(String name) { 2449 name = resolveName(name); 2450 2451 Module module = getModule(); 2452 if (module.isNamed()) { 2453 if (!ResourceHelper.isSimpleResource(name)) { 2454 Module caller = Reflection.getCallerClass().getModule(); 2455 if (caller != module) { 2456 Set<String> packages = module.getDescriptor().packages(); 2457 String pn = ResourceHelper.getPackageName(name); 2458 if (packages.contains(pn) && !module.isOpen(pn, caller)) { 2459 // resource is in package not open to caller 2460 return null; 2461 } 2462 } 2463 } 2464 2465 String mn = module.getName(); 2466 ClassLoader cl = getClassLoader0(); 2467 try { 2468 2469 // special-case built-in class loaders to avoid the 2470 // need for a URL connection 2471 if (cl == null) { 2472 return BootLoader.findResourceAsStream(mn, name); 2473 } else if (cl instanceof BuiltinClassLoader) { 2474 return ((BuiltinClassLoader) cl).findResourceAsStream(mn, name); 2475 } else { 2476 URL url = cl.findResource(mn, name); 2477 return (url != null) ? url.openStream() : null; 2478 } 2479 2480 } catch (IOException | SecurityException e) { 2481 return null; 2482 } 2483 } 2484 2485 // unnamed module 2486 ClassLoader cl = getClassLoader0(); 2487 if (cl == null) { 2488 return ClassLoader.getSystemResourceAsStream(name); 2489 } else { 2490 return cl.getResourceAsStream(name); 2491 } 2492 } 2493 2494 /** 2495 * Finds a resource with a given name. 2496 * 2497 * <p> If this class is in a named {@link Module Module} then this method 2498 * will attempt to find the resource in the module by means of the absolute 2499 * resource name, subject to the rules for encapsulation specified in the 2500 * {@code Module} {@link Module#getResourceAsStream getResourceAsStream} 2501 * method. 2502 * 2503 * <p> Otherwise, if this class is not in a named module then the rules for 2504 * searching resources associated with a given class are implemented by the 2505 * defining {@linkplain ClassLoader class loader} of the class. This method 2506 * delegates to this object's class loader. If this object was loaded by 2507 * the bootstrap class loader, the method delegates to {@link 2508 * ClassLoader#getSystemResource}. 2509 * 2510 * <p> Before delegation, an absolute resource name is constructed from the 2511 * given resource name using this algorithm: 2512 * 2513 * <ul> 2514 * 2515 * <li> If the {@code name} begins with a {@code '/'} 2516 * (<tt>'\u002f'</tt>), then the absolute name of the resource is the 2517 * portion of the {@code name} following the {@code '/'}. 2518 * 2519 * <li> Otherwise, the absolute name is of the following form: 2520 * 2521 * <blockquote> 2522 * {@code modified_package_name/name} 2523 * </blockquote> 2524 * 2525 * <p> Where the {@code modified_package_name} is the package name of this 2526 * object with {@code '/'} substituted for {@code '.'} 2527 * (<tt>'\u002e'</tt>). 2528 * 2529 * </ul> 2530 * 2531 * @param name name of the desired resource 2532 * @return A {@link java.net.URL} object; {@code null} if no resource with 2533 * this name is found, the resource cannot be located by a URL, the 2534 * resource is in a package that is not 2535 * {@link Module#isOpen(String, Module) open} to at least the caller 2536 * module, or access to the resource is denied by the security 2537 * manager. 2538 * @throws NullPointerException If {@code name} is {@code null} 2539 * @since 1.1 2540 */ 2541 @CallerSensitive 2542 public URL getResource(String name) { 2543 name = resolveName(name); 2544 2545 Module module = getModule(); 2546 if (module.isNamed()) { 2547 if (!ResourceHelper.isSimpleResource(name)) { 2548 Module caller = Reflection.getCallerClass().getModule(); 2549 if (caller != module) { 2550 Set<String> packages = module.getDescriptor().packages(); 2551 String pn = ResourceHelper.getPackageName(name); 2552 if (packages.contains(pn) && !module.isOpen(pn, caller)) { 2553 // resource is in package not open to caller 2554 return null; 2555 } 2556 } 2557 } 2558 String mn = getModule().getName(); 2559 ClassLoader cl = getClassLoader0(); 2560 try { 2561 if (cl == null) { 2562 return BootLoader.findResource(mn, name); 2563 } else { 2564 return cl.findResource(mn, name); 2565 } 2566 } catch (IOException ioe) { 2567 return null; 2568 } 2569 } 2570 2571 // unnamed module 2572 ClassLoader cl = getClassLoader0(); 2573 if (cl == null) { 2574 return ClassLoader.getSystemResource(name); 2575 } else { 2576 return cl.getResource(name); 2577 } 2578 } 2579 2580 /** protection domain returned when the internal domain is null */ 2581 private static java.security.ProtectionDomain allPermDomain; 2582 2583 2584 /** 2585 * Returns the {@code ProtectionDomain} of this class. If there is a 2586 * security manager installed, this method first calls the security 2587 * manager's {@code checkPermission} method with a 2588 * {@code RuntimePermission("getProtectionDomain")} permission to 2589 * ensure it's ok to get the 2590 * {@code ProtectionDomain}. 2591 * 2592 * @return the ProtectionDomain of this class 2593 * 2594 * @throws SecurityException 2595 * if a security manager exists and its 2596 * {@code checkPermission} method doesn't allow 2597 * getting the ProtectionDomain. 2598 * 2599 * @see java.security.ProtectionDomain 2600 * @see SecurityManager#checkPermission 2601 * @see java.lang.RuntimePermission 2602 * @since 1.2 2603 */ 2604 public java.security.ProtectionDomain getProtectionDomain() { 2605 SecurityManager sm = System.getSecurityManager(); 2606 if (sm != null) { 2607 sm.checkPermission(SecurityConstants.GET_PD_PERMISSION); 2608 } 2609 java.security.ProtectionDomain pd = getProtectionDomain0(); 2610 if (pd == null) { 2611 if (allPermDomain == null) { 2612 java.security.Permissions perms = 2613 new java.security.Permissions(); 2614 perms.add(SecurityConstants.ALL_PERMISSION); 2615 allPermDomain = 2616 new java.security.ProtectionDomain(null, perms); 2617 } 2618 pd = allPermDomain; 2619 } 2620 return pd; 2621 } 2622 2623 2624 /** 2625 * Returns the ProtectionDomain of this class. 2626 */ 2627 private native java.security.ProtectionDomain getProtectionDomain0(); 2628 2629 /* 2630 * Return the Virtual Machine's Class object for the named 2631 * primitive type. 2632 */ 2633 static native Class<?> getPrimitiveClass(String name); 2634 2635 /* 2636 * Check if client is allowed to access members. If access is denied, 2637 * throw a SecurityException. 2638 * 2639 * This method also enforces package access. 2640 * 2641 * <p> Default policy: allow all clients access with normal Java access 2642 * control. 2643 */ 2644 private void checkMemberAccess(int which, Class<?> caller, boolean checkProxyInterfaces) { 2645 final SecurityManager s = System.getSecurityManager(); 2646 if (s != null) { 2647 /* Default policy allows access to all {@link Member#PUBLIC} members, 2648 * as well as access to classes that have the same class loader as the caller. 2649 * In all other cases, it requires RuntimePermission("accessDeclaredMembers") 2650 * permission. 2651 */ 2652 final ClassLoader ccl = ClassLoader.getClassLoader(caller); 2653 final ClassLoader cl = getClassLoader0(); 2654 if (which != Member.PUBLIC) { 2655 if (ccl != cl) { 2656 s.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION); 2657 } 2658 } 2659 this.checkPackageAccess(ccl, checkProxyInterfaces); 2660 } 2661 } 2662 2663 /* 2664 * Checks if a client loaded in ClassLoader ccl is allowed to access this 2665 * class under the current package access policy. If access is denied, 2666 * throw a SecurityException. 2667 */ 2668 private void checkPackageAccess(final ClassLoader ccl, boolean checkProxyInterfaces) { 2669 final SecurityManager s = System.getSecurityManager(); 2670 if (s != null) { 2671 final ClassLoader cl = getClassLoader0(); 2672 2673 if (ReflectUtil.needsPackageAccessCheck(ccl, cl)) { 2674 String name = this.getName(); 2675 int i = name.lastIndexOf('.'); 2676 if (i != -1) { 2677 // skip the package access check on a proxy class in default proxy package 2678 String pkg = name.substring(0, i); 2679 if (!Proxy.isProxyClass(this) || ReflectUtil.isNonPublicProxyClass(this)) { 2680 s.checkPackageAccess(pkg); 2681 } 2682 } 2683 } 2684 // check package access on the proxy interfaces 2685 if (checkProxyInterfaces && Proxy.isProxyClass(this)) { 2686 ReflectUtil.checkProxyPackageAccess(ccl, this.getInterfaces()); 2687 } 2688 } 2689 } 2690 2691 /** 2692 * Add a package name prefix if the name is not absolute Remove leading "/" 2693 * if name is absolute 2694 */ 2695 private String resolveName(String name) { 2696 if (!name.startsWith("/")) { 2697 Class<?> c = this; 2698 while (c.isArray()) { 2699 c = c.getComponentType(); 2700 } 2701 String baseName = c.getName(); 2702 int index = baseName.lastIndexOf('.'); 2703 if (index != -1) { 2704 name = baseName.substring(0, index).replace('.', '/') 2705 +"/"+name; 2706 } 2707 } else { 2708 name = name.substring(1); 2709 } 2710 return name; 2711 } 2712 2713 /** 2714 * Atomic operations support. 2715 */ 2716 private static class Atomic { 2717 // initialize Unsafe machinery here, since we need to call Class.class instance method 2718 // and have to avoid calling it in the static initializer of the Class class... 2719 private static final Unsafe unsafe = Unsafe.getUnsafe(); 2720 // offset of Class.reflectionData instance field 2721 private static final long reflectionDataOffset; 2722 // offset of Class.annotationType instance field 2723 private static final long annotationTypeOffset; 2724 // offset of Class.annotationData instance field 2725 private static final long annotationDataOffset; 2726 2727 static { 2728 Field[] fields = Class.class.getDeclaredFields0(false); // bypass caches 2729 reflectionDataOffset = objectFieldOffset(fields, "reflectionData"); 2730 annotationTypeOffset = objectFieldOffset(fields, "annotationType"); 2731 annotationDataOffset = objectFieldOffset(fields, "annotationData"); 2732 } 2733 2734 private static long objectFieldOffset(Field[] fields, String fieldName) { 2735 Field field = searchFields(fields, fieldName); 2736 if (field == null) { 2737 throw new Error("No " + fieldName + " field found in java.lang.Class"); 2738 } 2739 return unsafe.objectFieldOffset(field); 2740 } 2741 2742 static <T> boolean casReflectionData(Class<?> clazz, 2743 SoftReference<ReflectionData<T>> oldData, 2744 SoftReference<ReflectionData<T>> newData) { 2745 return unsafe.compareAndSwapObject(clazz, reflectionDataOffset, oldData, newData); 2746 } 2747 2748 static <T> boolean casAnnotationType(Class<?> clazz, 2749 AnnotationType oldType, 2750 AnnotationType newType) { 2751 return unsafe.compareAndSwapObject(clazz, annotationTypeOffset, oldType, newType); 2752 } 2753 2754 static <T> boolean casAnnotationData(Class<?> clazz, 2755 AnnotationData oldData, 2756 AnnotationData newData) { 2757 return unsafe.compareAndSwapObject(clazz, annotationDataOffset, oldData, newData); 2758 } 2759 } 2760 2761 /** 2762 * Reflection support. 2763 */ 2764 2765 // reflection data that might get invalidated when JVM TI RedefineClasses() is called 2766 private static class ReflectionData<T> { 2767 volatile Field[] declaredFields; 2768 volatile Field[] publicFields; 2769 volatile Method[] declaredMethods; 2770 volatile Method[] publicMethods; 2771 volatile Constructor<T>[] declaredConstructors; 2772 volatile Constructor<T>[] publicConstructors; 2773 // Intermediate results for getFields and getMethods 2774 volatile Field[] declaredPublicFields; 2775 volatile Method[] declaredPublicMethods; 2776 volatile Class<?>[] interfaces; 2777 2778 // Value of classRedefinedCount when we created this ReflectionData instance 2779 final int redefinedCount; 2780 2781 ReflectionData(int redefinedCount) { 2782 this.redefinedCount = redefinedCount; 2783 } 2784 } 2785 2786 private transient volatile SoftReference<ReflectionData<T>> reflectionData; 2787 2788 // Incremented by the VM on each call to JVM TI RedefineClasses() 2789 // that redefines this class or a superclass. 2790 private transient volatile int classRedefinedCount; 2791 2792 // Lazily create and cache ReflectionData 2793 private ReflectionData<T> reflectionData() { 2794 SoftReference<ReflectionData<T>> reflectionData = this.reflectionData; 2795 int classRedefinedCount = this.classRedefinedCount; 2796 ReflectionData<T> rd; 2797 if (reflectionData != null && 2798 (rd = reflectionData.get()) != null && 2799 rd.redefinedCount == classRedefinedCount) { 2800 return rd; 2801 } 2802 // else no SoftReference or cleared SoftReference or stale ReflectionData 2803 // -> create and replace new instance 2804 return newReflectionData(reflectionData, classRedefinedCount); 2805 } 2806 2807 private ReflectionData<T> newReflectionData(SoftReference<ReflectionData<T>> oldReflectionData, 2808 int classRedefinedCount) { 2809 while (true) { 2810 ReflectionData<T> rd = new ReflectionData<>(classRedefinedCount); 2811 // try to CAS it... 2812 if (Atomic.casReflectionData(this, oldReflectionData, new SoftReference<>(rd))) { 2813 return rd; 2814 } 2815 // else retry 2816 oldReflectionData = this.reflectionData; 2817 classRedefinedCount = this.classRedefinedCount; 2818 if (oldReflectionData != null && 2819 (rd = oldReflectionData.get()) != null && 2820 rd.redefinedCount == classRedefinedCount) { 2821 return rd; 2822 } 2823 } 2824 } 2825 2826 // Generic signature handling 2827 private native String getGenericSignature0(); 2828 2829 // Generic info repository; lazily initialized 2830 private transient volatile ClassRepository genericInfo; 2831 2832 // accessor for factory 2833 private GenericsFactory getFactory() { 2834 // create scope and factory 2835 return CoreReflectionFactory.make(this, ClassScope.make(this)); 2836 } 2837 2838 // accessor for generic info repository; 2839 // generic info is lazily initialized 2840 private ClassRepository getGenericInfo() { 2841 ClassRepository genericInfo = this.genericInfo; 2842 if (genericInfo == null) { 2843 String signature = getGenericSignature0(); 2844 if (signature == null) { 2845 genericInfo = ClassRepository.NONE; 2846 } else { 2847 genericInfo = ClassRepository.make(signature, getFactory()); 2848 } 2849 this.genericInfo = genericInfo; 2850 } 2851 return (genericInfo != ClassRepository.NONE) ? genericInfo : null; 2852 } 2853 2854 // Annotations handling 2855 native byte[] getRawAnnotations(); 2856 // Since 1.8 2857 native byte[] getRawTypeAnnotations(); 2858 static byte[] getExecutableTypeAnnotationBytes(Executable ex) { 2859 return getReflectionFactory().getExecutableTypeAnnotationBytes(ex); 2860 } 2861 2862 native ConstantPool getConstantPool(); 2863 2864 // 2865 // 2866 // java.lang.reflect.Field handling 2867 // 2868 // 2869 2870 // Returns an array of "root" fields. These Field objects must NOT 2871 // be propagated to the outside world, but must instead be copied 2872 // via ReflectionFactory.copyField. 2873 private Field[] privateGetDeclaredFields(boolean publicOnly) { 2874 Field[] res; 2875 ReflectionData<T> rd = reflectionData(); 2876 if (rd != null) { 2877 res = publicOnly ? rd.declaredPublicFields : rd.declaredFields; 2878 if (res != null) return res; 2879 } 2880 // No cached value available; request value from VM 2881 res = Reflection.filterFields(this, getDeclaredFields0(publicOnly)); 2882 if (rd != null) { 2883 if (publicOnly) { 2884 rd.declaredPublicFields = res; 2885 } else { 2886 rd.declaredFields = res; 2887 } 2888 } 2889 return res; 2890 } 2891 2892 // Returns an array of "root" fields. These Field objects must NOT 2893 // be propagated to the outside world, but must instead be copied 2894 // via ReflectionFactory.copyField. 2895 private Field[] privateGetPublicFields(Set<Class<?>> traversedInterfaces) { 2896 Field[] res; 2897 ReflectionData<T> rd = reflectionData(); 2898 if (rd != null) { 2899 res = rd.publicFields; 2900 if (res != null) return res; 2901 } 2902 2903 // No cached value available; compute value recursively. 2904 // Traverse in correct order for getField(). 2905 List<Field> fields = new ArrayList<>(); 2906 if (traversedInterfaces == null) { 2907 traversedInterfaces = new HashSet<>(); 2908 } 2909 2910 // Local fields 2911 Field[] tmp = privateGetDeclaredFields(true); 2912 addAll(fields, tmp); 2913 2914 // Direct superinterfaces, recursively 2915 for (Class<?> c : getInterfaces()) { 2916 if (!traversedInterfaces.contains(c)) { 2917 traversedInterfaces.add(c); 2918 addAll(fields, c.privateGetPublicFields(traversedInterfaces)); 2919 } 2920 } 2921 2922 // Direct superclass, recursively 2923 if (!isInterface()) { 2924 Class<?> c = getSuperclass(); 2925 if (c != null) { 2926 addAll(fields, c.privateGetPublicFields(traversedInterfaces)); 2927 } 2928 } 2929 2930 res = new Field[fields.size()]; 2931 fields.toArray(res); 2932 if (rd != null) { 2933 rd.publicFields = res; 2934 } 2935 return res; 2936 } 2937 2938 private static void addAll(Collection<Field> c, Field[] o) { 2939 for (Field f : o) { 2940 c.add(f); 2941 } 2942 } 2943 2944 2945 // 2946 // 2947 // java.lang.reflect.Constructor handling 2948 // 2949 // 2950 2951 // Returns an array of "root" constructors. These Constructor 2952 // objects must NOT be propagated to the outside world, but must 2953 // instead be copied via ReflectionFactory.copyConstructor. 2954 private Constructor<T>[] privateGetDeclaredConstructors(boolean publicOnly) { 2955 Constructor<T>[] res; 2956 ReflectionData<T> rd = reflectionData(); 2957 if (rd != null) { 2958 res = publicOnly ? rd.publicConstructors : rd.declaredConstructors; 2959 if (res != null) return res; 2960 } 2961 // No cached value available; request value from VM 2962 if (isInterface()) { 2963 @SuppressWarnings("unchecked") 2964 Constructor<T>[] temporaryRes = (Constructor<T>[]) new Constructor<?>[0]; 2965 res = temporaryRes; 2966 } else { 2967 res = getDeclaredConstructors0(publicOnly); 2968 } 2969 if (rd != null) { 2970 if (publicOnly) { 2971 rd.publicConstructors = res; 2972 } else { 2973 rd.declaredConstructors = res; 2974 } 2975 } 2976 return res; 2977 } 2978 2979 // 2980 // 2981 // java.lang.reflect.Method handling 2982 // 2983 // 2984 2985 // Returns an array of "root" methods. These Method objects must NOT 2986 // be propagated to the outside world, but must instead be copied 2987 // via ReflectionFactory.copyMethod. 2988 private Method[] privateGetDeclaredMethods(boolean publicOnly) { 2989 Method[] res; 2990 ReflectionData<T> rd = reflectionData(); 2991 if (rd != null) { 2992 res = publicOnly ? rd.declaredPublicMethods : rd.declaredMethods; 2993 if (res != null) return res; 2994 } 2995 // No cached value available; request value from VM 2996 res = Reflection.filterMethods(this, getDeclaredMethods0(publicOnly)); 2997 if (rd != null) { 2998 if (publicOnly) { 2999 rd.declaredPublicMethods = res; 3000 } else { 3001 rd.declaredMethods = res; 3002 } 3003 } 3004 return res; 3005 } 3006 3007 static class MethodArray { 3008 // Don't add or remove methods except by add() or remove() calls. 3009 private Method[] methods; 3010 private int length; 3011 private int defaults; 3012 3013 MethodArray() { 3014 this(20); 3015 } 3016 3017 MethodArray(int initialSize) { 3018 if (initialSize < 2) 3019 throw new IllegalArgumentException("Size should be 2 or more"); 3020 3021 methods = new Method[initialSize]; 3022 length = 0; 3023 defaults = 0; 3024 } 3025 3026 boolean hasDefaults() { 3027 return defaults != 0; 3028 } 3029 3030 void add(Method m) { 3031 if (length == methods.length) { 3032 methods = Arrays.copyOf(methods, 2 * methods.length); 3033 } 3034 methods[length++] = m; 3035 3036 if (m != null && m.isDefault()) 3037 defaults++; 3038 } 3039 3040 void addAll(Method[] ma) { 3041 for (Method m : ma) { 3042 add(m); 3043 } 3044 } 3045 3046 void addAll(MethodArray ma) { 3047 for (int i = 0; i < ma.length(); i++) { 3048 add(ma.get(i)); 3049 } 3050 } 3051 3052 void addIfNotPresent(Method newMethod) { 3053 for (int i = 0; i < length; i++) { 3054 Method m = methods[i]; 3055 if (m == newMethod || (m != null && m.equals(newMethod))) { 3056 return; 3057 } 3058 } 3059 add(newMethod); 3060 } 3061 3062 void addAllIfNotPresent(MethodArray newMethods) { 3063 for (int i = 0; i < newMethods.length(); i++) { 3064 Method m = newMethods.get(i); 3065 if (m != null) { 3066 addIfNotPresent(m); 3067 } 3068 } 3069 } 3070 3071 /* Add Methods declared in an interface to this MethodArray. 3072 * Static methods declared in interfaces are not inherited. 3073 */ 3074 void addInterfaceMethods(Method[] methods) { 3075 for (Method candidate : methods) { 3076 if (!Modifier.isStatic(candidate.getModifiers())) { 3077 add(candidate); 3078 } 3079 } 3080 } 3081 3082 int length() { 3083 return length; 3084 } 3085 3086 Method get(int i) { 3087 return methods[i]; 3088 } 3089 3090 Method getFirst() { 3091 for (Method m : methods) 3092 if (m != null) 3093 return m; 3094 return null; 3095 } 3096 3097 void removeByNameAndDescriptor(Method toRemove) { 3098 for (int i = 0; i < length; i++) { 3099 Method m = methods[i]; 3100 if (m != null && matchesNameAndDescriptor(m, toRemove)) { 3101 remove(i); 3102 } 3103 } 3104 } 3105 3106 private void remove(int i) { 3107 if (methods[i] != null && methods[i].isDefault()) 3108 defaults--; 3109 methods[i] = null; 3110 } 3111 3112 private boolean matchesNameAndDescriptor(Method m1, Method m2) { 3113 return m1.getReturnType() == m2.getReturnType() && 3114 m1.getName() == m2.getName() && // name is guaranteed to be interned 3115 arrayContentsEq(m1.getParameterTypes(), 3116 m2.getParameterTypes()); 3117 } 3118 3119 void compactAndTrim() { 3120 int newPos = 0; 3121 // Get rid of null slots 3122 for (int pos = 0; pos < length; pos++) { 3123 Method m = methods[pos]; 3124 if (m != null) { 3125 if (pos != newPos) { 3126 methods[newPos] = m; 3127 } 3128 newPos++; 3129 } 3130 } 3131 if (newPos != methods.length) { 3132 methods = Arrays.copyOf(methods, newPos); 3133 } 3134 } 3135 3136 /* Removes all Methods from this MethodArray that have a more specific 3137 * default Method in this MethodArray. 3138 * 3139 * Users of MethodArray are responsible for pruning Methods that have 3140 * a more specific <em>concrete</em> Method. 3141 */ 3142 void removeLessSpecifics() { 3143 if (!hasDefaults()) 3144 return; 3145 3146 for (int i = 0; i < length; i++) { 3147 Method m = get(i); 3148 if (m == null || !m.isDefault()) 3149 continue; 3150 3151 for (int j = 0; j < length; j++) { 3152 if (i == j) 3153 continue; 3154 3155 Method candidate = get(j); 3156 if (candidate == null) 3157 continue; 3158 3159 if (!matchesNameAndDescriptor(m, candidate)) 3160 continue; 3161 3162 if (hasMoreSpecificClass(m, candidate)) 3163 remove(j); 3164 } 3165 } 3166 } 3167 3168 Method[] getArray() { 3169 return methods; 3170 } 3171 3172 // Returns true if m1 is more specific than m2 3173 static boolean hasMoreSpecificClass(Method m1, Method m2) { 3174 Class<?> m1Class = m1.getDeclaringClass(); 3175 Class<?> m2Class = m2.getDeclaringClass(); 3176 return m1Class != m2Class && m2Class.isAssignableFrom(m1Class); 3177 } 3178 } 3179 3180 3181 // Returns an array of "root" methods. These Method objects must NOT 3182 // be propagated to the outside world, but must instead be copied 3183 // via ReflectionFactory.copyMethod. 3184 private Method[] privateGetPublicMethods() { 3185 Method[] res; 3186 ReflectionData<T> rd = reflectionData(); 3187 if (rd != null) { 3188 res = rd.publicMethods; 3189 if (res != null) return res; 3190 } 3191 3192 // No cached value available; compute value recursively. 3193 // Start by fetching public declared methods 3194 MethodArray methods = new MethodArray(); 3195 { 3196 Method[] tmp = privateGetDeclaredMethods(true); 3197 methods.addAll(tmp); 3198 } 3199 // Now recur over superclass and direct superinterfaces. 3200 // Go over superinterfaces first so we can more easily filter 3201 // out concrete implementations inherited from superclasses at 3202 // the end. 3203 MethodArray inheritedMethods = new MethodArray(); 3204 for (Class<?> i : getInterfaces()) { 3205 inheritedMethods.addInterfaceMethods(i.privateGetPublicMethods()); 3206 } 3207 if (!isInterface()) { 3208 Class<?> c = getSuperclass(); 3209 if (c != null) { 3210 MethodArray supers = new MethodArray(); 3211 supers.addAll(c.privateGetPublicMethods()); 3212 // Filter out concrete implementations of any 3213 // interface methods 3214 for (int i = 0; i < supers.length(); i++) { 3215 Method m = supers.get(i); 3216 if (m != null && 3217 !Modifier.isAbstract(m.getModifiers()) && 3218 !m.isDefault()) { 3219 inheritedMethods.removeByNameAndDescriptor(m); 3220 } 3221 } 3222 // Insert superclass's inherited methods before 3223 // superinterfaces' to satisfy getMethod's search 3224 // order 3225 supers.addAll(inheritedMethods); 3226 inheritedMethods = supers; 3227 } 3228 } 3229 // Filter out all local methods from inherited ones 3230 for (int i = 0; i < methods.length(); i++) { 3231 Method m = methods.get(i); 3232 inheritedMethods.removeByNameAndDescriptor(m); 3233 } 3234 methods.addAllIfNotPresent(inheritedMethods); 3235 methods.removeLessSpecifics(); 3236 methods.compactAndTrim(); 3237 res = methods.getArray(); 3238 if (rd != null) { 3239 rd.publicMethods = res; 3240 } 3241 return res; 3242 } 3243 3244 3245 // 3246 // Helpers for fetchers of one field, method, or constructor 3247 // 3248 3249 private static Field searchFields(Field[] fields, String name) { 3250 String internedName = name.intern(); 3251 for (Field field : fields) { 3252 if (field.getName() == internedName) { 3253 return getReflectionFactory().copyField(field); 3254 } 3255 } 3256 return null; 3257 } 3258 3259 private Field getField0(String name) throws NoSuchFieldException { 3260 // Note: the intent is that the search algorithm this routine 3261 // uses be equivalent to the ordering imposed by 3262 // privateGetPublicFields(). It fetches only the declared 3263 // public fields for each class, however, to reduce the number 3264 // of Field objects which have to be created for the common 3265 // case where the field being requested is declared in the 3266 // class which is being queried. 3267 Field res; 3268 // Search declared public fields 3269 if ((res = searchFields(privateGetDeclaredFields(true), name)) != null) { 3270 return res; 3271 } 3272 // Direct superinterfaces, recursively 3273 Class<?>[] interfaces = getInterfaces(); 3274 for (Class<?> c : interfaces) { 3275 if ((res = c.getField0(name)) != null) { 3276 return res; 3277 } 3278 } 3279 // Direct superclass, recursively 3280 if (!isInterface()) { 3281 Class<?> c = getSuperclass(); 3282 if (c != null) { 3283 if ((res = c.getField0(name)) != null) { 3284 return res; 3285 } 3286 } 3287 } 3288 return null; 3289 } 3290 3291 private static Method searchMethods(Method[] methods, 3292 String name, 3293 Class<?>[] parameterTypes) 3294 { 3295 Method res = null; 3296 String internedName = name.intern(); 3297 for (Method m : methods) { 3298 if (m.getName() == internedName 3299 && arrayContentsEq(parameterTypes, m.getParameterTypes()) 3300 && (res == null 3301 || res.getReturnType().isAssignableFrom(m.getReturnType()))) 3302 res = m; 3303 } 3304 3305 return (res == null ? res : getReflectionFactory().copyMethod(res)); 3306 } 3307 3308 private Method getMethod0(String name, Class<?>[] parameterTypes, boolean includeStaticMethods) { 3309 MethodArray interfaceCandidates = new MethodArray(2); 3310 Method res = privateGetMethodRecursive(name, parameterTypes, includeStaticMethods, interfaceCandidates); 3311 if (res != null) 3312 return res; 3313 3314 // Not found on class or superclass directly 3315 interfaceCandidates.removeLessSpecifics(); 3316 return interfaceCandidates.getFirst(); // may be null 3317 } 3318 3319 private Method privateGetMethodRecursive(String name, 3320 Class<?>[] parameterTypes, 3321 boolean includeStaticMethods, 3322 MethodArray allInterfaceCandidates) { 3323 // Note: the intent is that the search algorithm this routine 3324 // uses be equivalent to the ordering imposed by 3325 // privateGetPublicMethods(). It fetches only the declared 3326 // public methods for each class, however, to reduce the 3327 // number of Method objects which have to be created for the 3328 // common case where the method being requested is declared in 3329 // the class which is being queried. 3330 // 3331 // Due to default methods, unless a method is found on a superclass, 3332 // methods declared in any superinterface needs to be considered. 3333 // Collect all candidates declared in superinterfaces in {@code 3334 // allInterfaceCandidates} and select the most specific if no match on 3335 // a superclass is found. 3336 3337 // Must _not_ return root methods 3338 Method res; 3339 // Search declared public methods 3340 if ((res = searchMethods(privateGetDeclaredMethods(true), 3341 name, 3342 parameterTypes)) != null) { 3343 if (includeStaticMethods || !Modifier.isStatic(res.getModifiers())) 3344 return res; 3345 } 3346 // Search superclass's methods 3347 if (!isInterface()) { 3348 Class<? super T> c = getSuperclass(); 3349 if (c != null) { 3350 if ((res = c.getMethod0(name, parameterTypes, true)) != null) { 3351 return res; 3352 } 3353 } 3354 } 3355 // Search superinterfaces' methods 3356 Class<?>[] interfaces = getInterfaces(); 3357 for (Class<?> c : interfaces) 3358 if ((res = c.getMethod0(name, parameterTypes, false)) != null) 3359 allInterfaceCandidates.add(res); 3360 // Not found 3361 return null; 3362 } 3363 3364 private Constructor<T> getConstructor0(Class<?>[] parameterTypes, 3365 int which) throws NoSuchMethodException 3366 { 3367 Constructor<T>[] constructors = privateGetDeclaredConstructors((which == Member.PUBLIC)); 3368 for (Constructor<T> constructor : constructors) { 3369 if (arrayContentsEq(parameterTypes, 3370 constructor.getParameterTypes())) { 3371 return getReflectionFactory().copyConstructor(constructor); 3372 } 3373 } 3374 throw new NoSuchMethodException(getName() + ".<init>" + argumentTypesToString(parameterTypes)); 3375 } 3376 3377 // 3378 // Other helpers and base implementation 3379 // 3380 3381 private static boolean arrayContentsEq(Object[] a1, Object[] a2) { 3382 if (a1 == null) { 3383 return a2 == null || a2.length == 0; 3384 } 3385 3386 if (a2 == null) { 3387 return a1.length == 0; 3388 } 3389 3390 if (a1.length != a2.length) { 3391 return false; 3392 } 3393 3394 for (int i = 0; i < a1.length; i++) { 3395 if (a1[i] != a2[i]) { 3396 return false; 3397 } 3398 } 3399 3400 return true; 3401 } 3402 3403 private static Field[] copyFields(Field[] arg) { 3404 Field[] out = new Field[arg.length]; 3405 ReflectionFactory fact = getReflectionFactory(); 3406 for (int i = 0; i < arg.length; i++) { 3407 out[i] = fact.copyField(arg[i]); 3408 } 3409 return out; 3410 } 3411 3412 private static Method[] copyMethods(Method[] arg) { 3413 Method[] out = new Method[arg.length]; 3414 ReflectionFactory fact = getReflectionFactory(); 3415 for (int i = 0; i < arg.length; i++) { 3416 out[i] = fact.copyMethod(arg[i]); 3417 } 3418 return out; 3419 } 3420 3421 private static <U> Constructor<U>[] copyConstructors(Constructor<U>[] arg) { 3422 Constructor<U>[] out = arg.clone(); 3423 ReflectionFactory fact = getReflectionFactory(); 3424 for (int i = 0; i < out.length; i++) { 3425 out[i] = fact.copyConstructor(out[i]); 3426 } 3427 return out; 3428 } 3429 3430 private native Field[] getDeclaredFields0(boolean publicOnly); 3431 private native Method[] getDeclaredMethods0(boolean publicOnly); 3432 private native Constructor<T>[] getDeclaredConstructors0(boolean publicOnly); 3433 private native Class<?>[] getDeclaredClasses0(); 3434 3435 private static String argumentTypesToString(Class<?>[] argTypes) { 3436 StringJoiner sj = new StringJoiner(", ", "(", ")"); 3437 if (argTypes != null) { 3438 for (int i = 0; i < argTypes.length; i++) { 3439 Class<?> c = argTypes[i]; 3440 sj.add((c == null) ? "null" : c.getName()); 3441 } 3442 } 3443 return sj.toString(); 3444 } 3445 3446 /** use serialVersionUID from JDK 1.1 for interoperability */ 3447 private static final long serialVersionUID = 3206093459760846163L; 3448 3449 3450 /** 3451 * Class Class is special cased within the Serialization Stream Protocol. 3452 * 3453 * A Class instance is written initially into an ObjectOutputStream in the 3454 * following format: 3455 * <pre> 3456 * {@code TC_CLASS} ClassDescriptor 3457 * A ClassDescriptor is a special cased serialization of 3458 * a {@code java.io.ObjectStreamClass} instance. 3459 * </pre> 3460 * A new handle is generated for the initial time the class descriptor 3461 * is written into the stream. Future references to the class descriptor 3462 * are written as references to the initial class descriptor instance. 3463 * 3464 * @see java.io.ObjectStreamClass 3465 */ 3466 private static final ObjectStreamField[] serialPersistentFields = 3467 new ObjectStreamField[0]; 3468 3469 3470 /** 3471 * Returns the assertion status that would be assigned to this 3472 * class if it were to be initialized at the time this method is invoked. 3473 * If this class has had its assertion status set, the most recent 3474 * setting will be returned; otherwise, if any package default assertion 3475 * status pertains to this class, the most recent setting for the most 3476 * specific pertinent package default assertion status is returned; 3477 * otherwise, if this class is not a system class (i.e., it has a 3478 * class loader) its class loader's default assertion status is returned; 3479 * otherwise, the system class default assertion status is returned. 3480 * <p> 3481 * Few programmers will have any need for this method; it is provided 3482 * for the benefit of the JRE itself. (It allows a class to determine at 3483 * the time that it is initialized whether assertions should be enabled.) 3484 * Note that this method is not guaranteed to return the actual 3485 * assertion status that was (or will be) associated with the specified 3486 * class when it was (or will be) initialized. 3487 * 3488 * @return the desired assertion status of the specified class. 3489 * @see java.lang.ClassLoader#setClassAssertionStatus 3490 * @see java.lang.ClassLoader#setPackageAssertionStatus 3491 * @see java.lang.ClassLoader#setDefaultAssertionStatus 3492 * @since 1.4 3493 */ 3494 public boolean desiredAssertionStatus() { 3495 ClassLoader loader = getClassLoader0(); 3496 // If the loader is null this is a system class, so ask the VM 3497 if (loader == null) 3498 return desiredAssertionStatus0(this); 3499 3500 // If the classloader has been initialized with the assertion 3501 // directives, ask it. Otherwise, ask the VM. 3502 synchronized(loader.assertionLock) { 3503 if (loader.classAssertionStatus != null) { 3504 return loader.desiredAssertionStatus(getName()); 3505 } 3506 } 3507 return desiredAssertionStatus0(this); 3508 } 3509 3510 // Retrieves the desired assertion status of this class from the VM 3511 private static native boolean desiredAssertionStatus0(Class<?> clazz); 3512 3513 /** 3514 * Returns true if and only if this class was declared as an enum in the 3515 * source code. 3516 * 3517 * @return true if and only if this class was declared as an enum in the 3518 * source code 3519 * @since 1.5 3520 */ 3521 public boolean isEnum() { 3522 // An enum must both directly extend java.lang.Enum and have 3523 // the ENUM bit set; classes for specialized enum constants 3524 // don't do the former. 3525 return (this.getModifiers() & ENUM) != 0 && 3526 this.getSuperclass() == java.lang.Enum.class; 3527 } 3528 3529 // Fetches the factory for reflective objects 3530 private static ReflectionFactory getReflectionFactory() { 3531 if (reflectionFactory == null) { 3532 reflectionFactory = 3533 java.security.AccessController.doPrivileged 3534 (new ReflectionFactory.GetReflectionFactoryAction()); 3535 } 3536 return reflectionFactory; 3537 } 3538 private static ReflectionFactory reflectionFactory; 3539 3540 /** 3541 * Returns the elements of this enum class or null if this 3542 * Class object does not represent an enum type. 3543 * 3544 * @return an array containing the values comprising the enum class 3545 * represented by this Class object in the order they're 3546 * declared, or null if this Class object does not 3547 * represent an enum type 3548 * @since 1.5 3549 */ 3550 public T[] getEnumConstants() { 3551 T[] values = getEnumConstantsShared(); 3552 return (values != null) ? values.clone() : null; 3553 } 3554 3555 /** 3556 * Returns the elements of this enum class or null if this 3557 * Class object does not represent an enum type; 3558 * identical to getEnumConstants except that the result is 3559 * uncloned, cached, and shared by all callers. 3560 */ 3561 T[] getEnumConstantsShared() { 3562 T[] constants = enumConstants; 3563 if (constants == null) { 3564 if (!isEnum()) return null; 3565 try { 3566 final Method values = getMethod("values"); 3567 java.security.AccessController.doPrivileged( 3568 new java.security.PrivilegedAction<>() { 3569 public Void run() { 3570 values.setAccessible(true); 3571 return null; 3572 } 3573 }); 3574 @SuppressWarnings("unchecked") 3575 T[] temporaryConstants = (T[])values.invoke(null); 3576 enumConstants = constants = temporaryConstants; 3577 } 3578 // These can happen when users concoct enum-like classes 3579 // that don't comply with the enum spec. 3580 catch (InvocationTargetException | NoSuchMethodException | 3581 IllegalAccessException ex) { return null; } 3582 } 3583 return constants; 3584 } 3585 private transient volatile T[] enumConstants; 3586 3587 /** 3588 * Returns a map from simple name to enum constant. This package-private 3589 * method is used internally by Enum to implement 3590 * {@code public static <T extends Enum<T>> T valueOf(Class<T>, String)} 3591 * efficiently. Note that the map is returned by this method is 3592 * created lazily on first use. Typically it won't ever get created. 3593 */ 3594 Map<String, T> enumConstantDirectory() { 3595 Map<String, T> directory = enumConstantDirectory; 3596 if (directory == null) { 3597 T[] universe = getEnumConstantsShared(); 3598 if (universe == null) 3599 throw new IllegalArgumentException( 3600 getName() + " is not an enum type"); 3601 directory = new HashMap<>(2 * universe.length); 3602 for (T constant : universe) { 3603 directory.put(((Enum<?>)constant).name(), constant); 3604 } 3605 enumConstantDirectory = directory; 3606 } 3607 return directory; 3608 } 3609 private transient volatile Map<String, T> enumConstantDirectory; 3610 3611 /** 3612 * Casts an object to the class or interface represented 3613 * by this {@code Class} object. 3614 * 3615 * @param obj the object to be cast 3616 * @return the object after casting, or null if obj is null 3617 * 3618 * @throws ClassCastException if the object is not 3619 * null and is not assignable to the type T. 3620 * 3621 * @since 1.5 3622 */ 3623 @SuppressWarnings("unchecked") 3624 @HotSpotIntrinsicCandidate 3625 public T cast(Object obj) { 3626 if (obj != null && !isInstance(obj)) 3627 throw new ClassCastException(cannotCastMsg(obj)); 3628 return (T) obj; 3629 } 3630 3631 private String cannotCastMsg(Object obj) { 3632 return "Cannot cast " + obj.getClass().getName() + " to " + getName(); 3633 } 3634 3635 /** 3636 * Casts this {@code Class} object to represent a subclass of the class 3637 * represented by the specified class object. Checks that the cast 3638 * is valid, and throws a {@code ClassCastException} if it is not. If 3639 * this method succeeds, it always returns a reference to this class object. 3640 * 3641 * <p>This method is useful when a client needs to "narrow" the type of 3642 * a {@code Class} object to pass it to an API that restricts the 3643 * {@code Class} objects that it is willing to accept. A cast would 3644 * generate a compile-time warning, as the correctness of the cast 3645 * could not be checked at runtime (because generic types are implemented 3646 * by erasure). 3647 * 3648 * @param <U> the type to cast this class object to 3649 * @param clazz the class of the type to cast this class object to 3650 * @return this {@code Class} object, cast to represent a subclass of 3651 * the specified class object. 3652 * @throws ClassCastException if this {@code Class} object does not 3653 * represent a subclass of the specified class (here "subclass" includes 3654 * the class itself). 3655 * @since 1.5 3656 */ 3657 @SuppressWarnings("unchecked") 3658 public <U> Class<? extends U> asSubclass(Class<U> clazz) { 3659 if (clazz.isAssignableFrom(this)) 3660 return (Class<? extends U>) this; 3661 else 3662 throw new ClassCastException(this.toString()); 3663 } 3664 3665 /** 3666 * @throws NullPointerException {@inheritDoc} 3667 * @since 1.5 3668 */ 3669 @SuppressWarnings("unchecked") 3670 public <A extends Annotation> A getAnnotation(Class<A> annotationClass) { 3671 Objects.requireNonNull(annotationClass); 3672 3673 return (A) annotationData().annotations.get(annotationClass); 3674 } 3675 3676 /** 3677 * {@inheritDoc} 3678 * @throws NullPointerException {@inheritDoc} 3679 * @since 1.5 3680 */ 3681 @Override 3682 public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) { 3683 return GenericDeclaration.super.isAnnotationPresent(annotationClass); 3684 } 3685 3686 /** 3687 * @throws NullPointerException {@inheritDoc} 3688 * @since 1.8 3689 */ 3690 @Override 3691 public <A extends Annotation> A[] getAnnotationsByType(Class<A> annotationClass) { 3692 Objects.requireNonNull(annotationClass); 3693 3694 AnnotationData annotationData = annotationData(); 3695 return AnnotationSupport.getAssociatedAnnotations(annotationData.declaredAnnotations, 3696 this, 3697 annotationClass); 3698 } 3699 3700 /** 3701 * @since 1.5 3702 */ 3703 public Annotation[] getAnnotations() { 3704 return AnnotationParser.toArray(annotationData().annotations); 3705 } 3706 3707 /** 3708 * @throws NullPointerException {@inheritDoc} 3709 * @since 1.8 3710 */ 3711 @Override 3712 @SuppressWarnings("unchecked") 3713 public <A extends Annotation> A getDeclaredAnnotation(Class<A> annotationClass) { 3714 Objects.requireNonNull(annotationClass); 3715 3716 return (A) annotationData().declaredAnnotations.get(annotationClass); 3717 } 3718 3719 /** 3720 * @throws NullPointerException {@inheritDoc} 3721 * @since 1.8 3722 */ 3723 @Override 3724 public <A extends Annotation> A[] getDeclaredAnnotationsByType(Class<A> annotationClass) { 3725 Objects.requireNonNull(annotationClass); 3726 3727 return AnnotationSupport.getDirectlyAndIndirectlyPresent(annotationData().declaredAnnotations, 3728 annotationClass); 3729 } 3730 3731 /** 3732 * @since 1.5 3733 */ 3734 public Annotation[] getDeclaredAnnotations() { 3735 return AnnotationParser.toArray(annotationData().declaredAnnotations); 3736 } 3737 3738 // annotation data that might get invalidated when JVM TI RedefineClasses() is called 3739 private static class AnnotationData { 3740 final Map<Class<? extends Annotation>, Annotation> annotations; 3741 final Map<Class<? extends Annotation>, Annotation> declaredAnnotations; 3742 3743 // Value of classRedefinedCount when we created this AnnotationData instance 3744 final int redefinedCount; 3745 3746 AnnotationData(Map<Class<? extends Annotation>, Annotation> annotations, 3747 Map<Class<? extends Annotation>, Annotation> declaredAnnotations, 3748 int redefinedCount) { 3749 this.annotations = annotations; 3750 this.declaredAnnotations = declaredAnnotations; 3751 this.redefinedCount = redefinedCount; 3752 } 3753 } 3754 3755 // Annotations cache 3756 @SuppressWarnings("UnusedDeclaration") 3757 private transient volatile AnnotationData annotationData; 3758 3759 private AnnotationData annotationData() { 3760 while (true) { // retry loop 3761 AnnotationData annotationData = this.annotationData; 3762 int classRedefinedCount = this.classRedefinedCount; 3763 if (annotationData != null && 3764 annotationData.redefinedCount == classRedefinedCount) { 3765 return annotationData; 3766 } 3767 // null or stale annotationData -> optimistically create new instance 3768 AnnotationData newAnnotationData = createAnnotationData(classRedefinedCount); 3769 // try to install it 3770 if (Atomic.casAnnotationData(this, annotationData, newAnnotationData)) { 3771 // successfully installed new AnnotationData 3772 return newAnnotationData; 3773 } 3774 } 3775 } 3776 3777 private AnnotationData createAnnotationData(int classRedefinedCount) { 3778 Map<Class<? extends Annotation>, Annotation> declaredAnnotations = 3779 AnnotationParser.parseAnnotations(getRawAnnotations(), getConstantPool(), this); 3780 Class<?> superClass = getSuperclass(); 3781 Map<Class<? extends Annotation>, Annotation> annotations = null; 3782 if (superClass != null) { 3783 Map<Class<? extends Annotation>, Annotation> superAnnotations = 3784 superClass.annotationData().annotations; 3785 for (Map.Entry<Class<? extends Annotation>, Annotation> e : superAnnotations.entrySet()) { 3786 Class<? extends Annotation> annotationClass = e.getKey(); 3787 if (AnnotationType.getInstance(annotationClass).isInherited()) { 3788 if (annotations == null) { // lazy construction 3789 annotations = new LinkedHashMap<>((Math.max( 3790 declaredAnnotations.size(), 3791 Math.min(12, declaredAnnotations.size() + superAnnotations.size()) 3792 ) * 4 + 2) / 3 3793 ); 3794 } 3795 annotations.put(annotationClass, e.getValue()); 3796 } 3797 } 3798 } 3799 if (annotations == null) { 3800 // no inherited annotations -> share the Map with declaredAnnotations 3801 annotations = declaredAnnotations; 3802 } else { 3803 // at least one inherited annotation -> declared may override inherited 3804 annotations.putAll(declaredAnnotations); 3805 } 3806 return new AnnotationData(annotations, declaredAnnotations, classRedefinedCount); 3807 } 3808 3809 // Annotation types cache their internal (AnnotationType) form 3810 3811 @SuppressWarnings("UnusedDeclaration") 3812 private transient volatile AnnotationType annotationType; 3813 3814 boolean casAnnotationType(AnnotationType oldType, AnnotationType newType) { 3815 return Atomic.casAnnotationType(this, oldType, newType); 3816 } 3817 3818 AnnotationType getAnnotationType() { 3819 return annotationType; 3820 } 3821 3822 Map<Class<? extends Annotation>, Annotation> getDeclaredAnnotationMap() { 3823 return annotationData().declaredAnnotations; 3824 } 3825 3826 /* Backing store of user-defined values pertaining to this class. 3827 * Maintained by the ClassValue class. 3828 */ 3829 transient ClassValue.ClassValueMap classValueMap; 3830 3831 /** 3832 * Returns an {@code AnnotatedType} object that represents the use of a 3833 * type to specify the superclass of the entity represented by this {@code 3834 * Class} object. (The <em>use</em> of type Foo to specify the superclass 3835 * in '... extends Foo' is distinct from the <em>declaration</em> of type 3836 * Foo.) 3837 * 3838 * <p> If this {@code Class} object represents a type whose declaration 3839 * does not explicitly indicate an annotated superclass, then the return 3840 * value is an {@code AnnotatedType} object representing an element with no 3841 * annotations. 3842 * 3843 * <p> If this {@code Class} represents either the {@code Object} class, an 3844 * interface type, an array type, a primitive type, or void, the return 3845 * value is {@code null}. 3846 * 3847 * @return an object representing the superclass 3848 * @since 1.8 3849 */ 3850 public AnnotatedType getAnnotatedSuperclass() { 3851 if (this == Object.class || 3852 isInterface() || 3853 isArray() || 3854 isPrimitive() || 3855 this == Void.TYPE) { 3856 return null; 3857 } 3858 3859 return TypeAnnotationParser.buildAnnotatedSuperclass(getRawTypeAnnotations(), getConstantPool(), this); 3860 } 3861 3862 /** 3863 * Returns an array of {@code AnnotatedType} objects that represent the use 3864 * of types to specify superinterfaces of the entity represented by this 3865 * {@code Class} object. (The <em>use</em> of type Foo to specify a 3866 * superinterface in '... implements Foo' is distinct from the 3867 * <em>declaration</em> of type Foo.) 3868 * 3869 * <p> If this {@code Class} object represents a class, the return value is 3870 * an array containing objects representing the uses of interface types to 3871 * specify interfaces implemented by the class. The order of the objects in 3872 * the array corresponds to the order of the interface types used in the 3873 * 'implements' clause of the declaration of this {@code Class} object. 3874 * 3875 * <p> If this {@code Class} object represents an interface, the return 3876 * value is an array containing objects representing the uses of interface 3877 * types to specify interfaces directly extended by the interface. The 3878 * order of the objects in the array corresponds to the order of the 3879 * interface types used in the 'extends' clause of the declaration of this 3880 * {@code Class} object. 3881 * 3882 * <p> If this {@code Class} object represents a class or interface whose 3883 * declaration does not explicitly indicate any annotated superinterfaces, 3884 * the return value is an array of length 0. 3885 * 3886 * <p> If this {@code Class} object represents either the {@code Object} 3887 * class, an array type, a primitive type, or void, the return value is an 3888 * array of length 0. 3889 * 3890 * @return an array representing the superinterfaces 3891 * @since 1.8 3892 */ 3893 public AnnotatedType[] getAnnotatedInterfaces() { 3894 return TypeAnnotationParser.buildAnnotatedInterfaces(getRawTypeAnnotations(), getConstantPool(), this); 3895 } 3896 }