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