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