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