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