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