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