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