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. The elements in the array returned are 1488 * not sorted and are not in any particular order. This method returns an 1489 * array of length 0 if the class or interface has no accessible public 1490 * fields, or if it represents an array class, a primitive type, or void. 1491 * 1492 * <p> Specifically, if this {@code Class} object represents a class, 1493 * this method returns the public fields of this class and of all its 1494 * superclasses. If this {@code Class} object represents an 1495 * interface, this method returns the fields of this interface and of all 1496 * its superinterfaces. 1497 * 1498 * <p> The implicit length field for array class is not reflected by this 1499 * method. User code should use the methods of class {@code Array} to 1500 * manipulate arrays. 1501 * 1502 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3. 1503 * 1504 * @return the array of {@code Field} objects representing the 1505 * public fields 1506 * @throws SecurityException 1507 * If a security manager, <i>s</i>, is present and 1508 * the caller's class loader is not the same as or an 1509 * ancestor of the class loader for the current class and 1510 * invocation of {@link SecurityManager#checkPackageAccess 1511 * s.checkPackageAccess()} denies access to the package 1512 * of this class. 1513 * 1514 * @since JDK1.1 1515 */ 1516 @CallerSensitive 1517 public Field[] getFields() throws SecurityException { 1518 checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true); 1519 return copyFields(privateGetPublicFields(null)); 1520 } 1521 1522 1523 /** 1524 * Returns an array containing {@code Method} objects reflecting all 1525 * the public <em>member</em> methods of the class or interface represented 1526 * by this {@code Class} object, including those declared by the class 1527 * or interface and those inherited from superclasses and 1528 * superinterfaces. Array classes return all the (public) member methods 1529 * inherited from the {@code Object} class. The elements in the array 1530 * returned are not sorted and are not in any particular order. This 1531 * method returns an array of length 0 if this {@code Class} object 1532 * represents a class or interface that has no public member methods, or if 1533 * this {@code Class} object represents a primitive type or void. 1534 * 1535 * <p> The class initialization method {@code <clinit>} is not 1536 * included in the returned array. If the class declares multiple public 1537 * member methods with the same parameter types, they are all included in 1538 * the returned array. 1539 * 1540 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.4. 1541 * 1542 * @return the array of {@code Method} objects representing the 1543 * public methods of this class 1544 * @throws SecurityException 1545 * If a security manager, <i>s</i>, is present and 1546 * the caller's class loader is not the same as or an 1547 * ancestor of the class loader for the current class and 1548 * invocation of {@link SecurityManager#checkPackageAccess 1549 * s.checkPackageAccess()} denies access to the package 1550 * of this class. 1551 * 1552 * @since JDK1.1 1553 */ 1554 @CallerSensitive 1555 public Method[] getMethods() throws SecurityException { 1556 checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true); 1557 return copyMethods(privateGetPublicMethods()); 1558 } 1559 1560 1561 /** 1562 * Returns an array containing {@code Constructor} objects reflecting 1563 * all the public constructors of the class represented by this 1564 * {@code Class} object. An array of length 0 is returned if the 1565 * class has no public constructors, or if the class is an array class, or 1566 * if the class reflects a primitive type or void. 1567 * 1568 * Note that while this method returns an array of {@code 1569 * Constructor<T>} objects (that is an array of constructors from 1570 * this class), the return type of this method is {@code 1571 * Constructor<?>[]} and <em>not</em> {@code Constructor<T>[]} as 1572 * might be expected. This less informative return type is 1573 * necessary since after being returned from this method, the 1574 * array could be modified to hold {@code Constructor} objects for 1575 * different classes, which would violate the type guarantees of 1576 * {@code Constructor<T>[]}. 1577 * 1578 * @return the array of {@code Constructor} objects representing the 1579 * public constructors of this class 1580 * @throws SecurityException 1581 * If a security manager, <i>s</i>, is present and 1582 * the caller's class loader is not the same as or an 1583 * ancestor of the class loader for the current class and 1584 * invocation of {@link SecurityManager#checkPackageAccess 1585 * s.checkPackageAccess()} denies access to the package 1586 * of this class. 1587 * 1588 * @since JDK1.1 1589 */ 1590 @CallerSensitive 1591 public Constructor<?>[] getConstructors() throws SecurityException { 1592 checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true); 1593 return copyConstructors(privateGetDeclaredConstructors(true)); 1594 } 1595 1596 1597 /** 1598 * Returns a {@code Field} object that reflects the specified public 1599 * member field of the class or interface represented by this 1600 * {@code Class} object. The {@code name} parameter is a 1601 * {@code String} specifying the simple name of the desired field. 1602 * 1603 * <p> The field to be reflected is determined by the algorithm that 1604 * follows. Let C be the class represented by this object: 1605 * <OL> 1606 * <LI> If C declares a public field with the name specified, that is the 1607 * field to be reflected.</LI> 1608 * <LI> If no field was found in step 1 above, this algorithm is applied 1609 * recursively to each direct superinterface of C. The direct 1610 * superinterfaces are searched in the order they were declared.</LI> 1611 * <LI> If no field was found in steps 1 and 2 above, and C has a 1612 * superclass S, then this algorithm is invoked recursively upon S. 1613 * If C has no superclass, then a {@code NoSuchFieldException} 1614 * is thrown.</LI> 1615 * </OL> 1616 * 1617 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3. 1618 * 1619 * @param name the field name 1620 * @return the {@code Field} object of this class specified by 1621 * {@code name} 1622 * @throws NoSuchFieldException if a field with the specified name is 1623 * not found. 1624 * @throws NullPointerException if {@code name} is {@code null} 1625 * @throws SecurityException 1626 * If a security manager, <i>s</i>, is present and 1627 * the caller's class loader is not the same as or an 1628 * ancestor of the class loader for the current class and 1629 * invocation of {@link SecurityManager#checkPackageAccess 1630 * s.checkPackageAccess()} denies access to the package 1631 * of this class. 1632 * 1633 * @since JDK1.1 1634 */ 1635 @CallerSensitive 1636 public Field getField(String name) 1637 throws NoSuchFieldException, SecurityException { 1638 checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true); 1639 Field field = getField0(name); 1640 if (field == null) { 1641 throw new NoSuchFieldException(name); 1642 } 1643 return field; 1644 } 1645 1646 1647 /** 1648 * Returns a {@code Method} object that reflects the specified public 1649 * member method of the class or interface represented by this 1650 * {@code Class} object. The {@code name} parameter is a 1651 * {@code String} specifying the simple name of the desired method. The 1652 * {@code parameterTypes} parameter is an array of {@code Class} 1653 * objects that identify the method's formal parameter types, in declared 1654 * order. If {@code parameterTypes} is {@code null}, it is 1655 * treated as if it were an empty array. 1656 * 1657 * <p> If the {@code name} is "{@code <init>};"or "{@code <clinit>}" a 1658 * {@code NoSuchMethodException} is raised. Otherwise, the method to 1659 * be reflected is determined by the algorithm that follows. Let C be the 1660 * class represented by this object: 1661 * <OL> 1662 * <LI> C is searched for any <I>matching methods</I>. If no matching 1663 * method is found, the algorithm of step 1 is invoked recursively on 1664 * the superclass of C.</LI> 1665 * <LI> If no method was found in step 1 above, the superinterfaces of C 1666 * are searched for a matching method. If any such method is found, it 1667 * is reflected.</LI> 1668 * </OL> 1669 * 1670 * To find a matching method in a class C: If C declares exactly one 1671 * public method with the specified name and exactly the same formal 1672 * parameter types, that is the method reflected. If more than one such 1673 * method is found in C, and one of these methods has a return type that is 1674 * more specific than any of the others, that method is reflected; 1675 * otherwise one of the methods is chosen arbitrarily. 1676 * 1677 * <p>Note that there may be more than one matching method in a 1678 * class because while the Java language forbids a class to 1679 * declare multiple methods with the same signature but different 1680 * return types, the Java virtual machine does not. This 1681 * increased flexibility in the virtual machine can be used to 1682 * implement various language features. For example, covariant 1683 * returns can be implemented with {@linkplain 1684 * java.lang.reflect.Method#isBridge bridge methods}; the bridge 1685 * method and the method being overridden would have the same 1686 * signature but different return types. 1687 * 1688 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.4. 1689 * 1690 * @param name the name of the method 1691 * @param parameterTypes the list of parameters 1692 * @return the {@code Method} object that matches the specified 1693 * {@code name} and {@code parameterTypes} 1694 * @throws NoSuchMethodException if a matching method is not found 1695 * or if the name is "<init>"or "<clinit>". 1696 * @throws NullPointerException if {@code name} is {@code null} 1697 * @throws SecurityException 1698 * If a security manager, <i>s</i>, is present and 1699 * the caller's class loader is not the same as or an 1700 * ancestor of the class loader for the current class and 1701 * invocation of {@link SecurityManager#checkPackageAccess 1702 * s.checkPackageAccess()} denies access to the package 1703 * of this class. 1704 * 1705 * @since JDK1.1 1706 */ 1707 @CallerSensitive 1708 public Method getMethod(String name, Class<?>... parameterTypes) 1709 throws NoSuchMethodException, SecurityException { 1710 checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true); 1711 Method method = getMethod0(name, parameterTypes); 1712 if (method == null) { 1713 throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes)); 1714 } 1715 return method; 1716 } 1717 1718 1719 /** 1720 * Returns a {@code Constructor} object that reflects the specified 1721 * public constructor of the class represented by this {@code Class} 1722 * object. The {@code parameterTypes} parameter is an array of 1723 * {@code Class} objects that identify the constructor's formal 1724 * parameter types, in declared order. 1725 * 1726 * If this {@code Class} object represents an inner class 1727 * declared in a non-static context, the formal parameter types 1728 * include the explicit enclosing instance as the first parameter. 1729 * 1730 * <p> The constructor to reflect is the public constructor of the class 1731 * represented by this {@code Class} object whose formal parameter 1732 * types match those specified by {@code parameterTypes}. 1733 * 1734 * @param parameterTypes the parameter array 1735 * @return the {@code Constructor} object of the public constructor that 1736 * matches the specified {@code parameterTypes} 1737 * @throws NoSuchMethodException if a matching method is not found. 1738 * @throws SecurityException 1739 * If a security manager, <i>s</i>, is present and 1740 * the caller's class loader is not the same as or an 1741 * ancestor of the class loader for the current class and 1742 * invocation of {@link SecurityManager#checkPackageAccess 1743 * s.checkPackageAccess()} denies access to the package 1744 * of this class. 1745 * 1746 * @since JDK1.1 1747 */ 1748 @CallerSensitive 1749 public Constructor<T> getConstructor(Class<?>... parameterTypes) 1750 throws NoSuchMethodException, SecurityException { 1751 checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true); 1752 return getConstructor0(parameterTypes, Member.PUBLIC); 1753 } 1754 1755 1756 /** 1757 * Returns an array of {@code Class} objects reflecting all the 1758 * classes and interfaces declared as members of the class represented by 1759 * this {@code Class} object. This includes public, protected, default 1760 * (package) access, and private classes and interfaces declared by the 1761 * class, but excludes inherited classes and interfaces. This method 1762 * returns an array of length 0 if the class declares no classes or 1763 * interfaces as members, or if this {@code Class} object represents a 1764 * primitive type, an array class, or void. 1765 * 1766 * @return the array of {@code Class} objects representing all the 1767 * declared members of this class 1768 * @throws SecurityException 1769 * If a security manager, <i>s</i>, is present and any of the 1770 * following conditions is met: 1771 * 1772 * <ul> 1773 * 1774 * <li> the caller's class loader is not the same as the 1775 * class loader of this class and invocation of 1776 * {@link SecurityManager#checkPermission 1777 * s.checkPermission} method with 1778 * {@code RuntimePermission("accessDeclaredMembers")} 1779 * denies access to the declared classes within this class 1780 * 1781 * <li> the caller's class loader is not the same as or an 1782 * ancestor of the class loader for the current class and 1783 * invocation of {@link SecurityManager#checkPackageAccess 1784 * s.checkPackageAccess()} denies access to the package 1785 * of this class 1786 * 1787 * </ul> 1788 * 1789 * @since JDK1.1 1790 */ 1791 @CallerSensitive 1792 public Class<?>[] getDeclaredClasses() throws SecurityException { 1793 checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), false); 1794 return getDeclaredClasses0(); 1795 } 1796 1797 1798 /** 1799 * Returns an array of {@code Field} objects reflecting all the fields 1800 * declared by the class or interface represented by this 1801 * {@code Class} object. This includes public, protected, default 1802 * (package) access, and private fields, but excludes inherited fields. 1803 * The elements in the array returned are not sorted and are not in any 1804 * particular order. This method returns an array of length 0 if the class 1805 * or interface declares no fields, or if this {@code Class} object 1806 * represents a primitive type, an array class, or void. 1807 * 1808 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3. 1809 * 1810 * @return the array of {@code Field} objects representing all the 1811 * declared fields of this class 1812 * @throws SecurityException 1813 * If a security manager, <i>s</i>, is present and any of the 1814 * following conditions is met: 1815 * 1816 * <ul> 1817 * 1818 * <li> the caller's class loader is not the same as the 1819 * class loader of this class and invocation of 1820 * {@link SecurityManager#checkPermission 1821 * s.checkPermission} method with 1822 * {@code RuntimePermission("accessDeclaredMembers")} 1823 * denies access to the declared fields within this class 1824 * 1825 * <li> the caller's class loader is not the same as or an 1826 * ancestor of the class loader for the current class and 1827 * invocation of {@link SecurityManager#checkPackageAccess 1828 * s.checkPackageAccess()} denies access to the package 1829 * of this class 1830 * 1831 * </ul> 1832 * 1833 * @since JDK1.1 1834 */ 1835 @CallerSensitive 1836 public Field[] getDeclaredFields() throws SecurityException { 1837 checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true); 1838 return copyFields(privateGetDeclaredFields(false)); 1839 } 1840 1841 1842 /** 1843 * Returns an array of {@code Method} objects reflecting all the 1844 * methods declared by the class or interface represented by this 1845 * {@code Class} object. This includes public, protected, default 1846 * (package) access, and private methods, but excludes inherited methods. 1847 * The elements in the array returned are not sorted and are not in any 1848 * particular order. This method returns an array of length 0 if the class 1849 * or interface declares no methods, or if this {@code Class} object 1850 * represents a primitive type, an array class, or void. The class 1851 * initialization method {@code <clinit>} is not included in the 1852 * returned array. If the class declares multiple public member methods 1853 * with the same parameter types, they are all included in the returned 1854 * array. 1855 * 1856 * <p> See <em>The Java Language Specification</em>, section 8.2. 1857 * 1858 * @return the array of {@code Method} objects representing all the 1859 * declared methods of this class 1860 * @throws SecurityException 1861 * If a security manager, <i>s</i>, is present and any of the 1862 * following conditions is met: 1863 * 1864 * <ul> 1865 * 1866 * <li> the caller's class loader is not the same as the 1867 * class loader of this class and invocation of 1868 * {@link SecurityManager#checkPermission 1869 * s.checkPermission} method with 1870 * {@code RuntimePermission("accessDeclaredMembers")} 1871 * denies access to the declared methods within this class 1872 * 1873 * <li> the caller's class loader is not the same as or an 1874 * ancestor of the class loader for the current class and 1875 * invocation of {@link SecurityManager#checkPackageAccess 1876 * s.checkPackageAccess()} denies access to the package 1877 * of this class 1878 * 1879 * </ul> 1880 * 1881 * @since JDK1.1 1882 */ 1883 @CallerSensitive 1884 public Method[] getDeclaredMethods() throws SecurityException { 1885 checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true); 1886 return copyMethods(privateGetDeclaredMethods(false)); 1887 } 1888 1889 1890 /** 1891 * Returns an array of {@code Constructor} objects reflecting all the 1892 * constructors declared by the class represented by this 1893 * {@code Class} object. These are public, protected, default 1894 * (package) access, and private constructors. The elements in the array 1895 * returned are not sorted and are not in any particular order. If the 1896 * class has a default constructor, it is included in the returned array. 1897 * This method returns an array of length 0 if this {@code Class} 1898 * object represents an interface, a primitive type, an array class, or 1899 * void. 1900 * 1901 * <p> See <em>The Java Language Specification</em>, section 8.2. 1902 * 1903 * @return the array of {@code Constructor} objects representing all the 1904 * declared constructors of this class 1905 * @throws SecurityException 1906 * If a security manager, <i>s</i>, is present and any of the 1907 * following conditions is met: 1908 * 1909 * <ul> 1910 * 1911 * <li> the caller's class loader is not the same as the 1912 * class loader of this class and invocation of 1913 * {@link SecurityManager#checkPermission 1914 * s.checkPermission} method with 1915 * {@code RuntimePermission("accessDeclaredMembers")} 1916 * denies access to the declared constructors within this class 1917 * 1918 * <li> the caller's class loader is not the same as or an 1919 * ancestor of the class loader for the current class and 1920 * invocation of {@link SecurityManager#checkPackageAccess 1921 * s.checkPackageAccess()} denies access to the package 1922 * of this class 1923 * 1924 * </ul> 1925 * 1926 * @since JDK1.1 1927 */ 1928 @CallerSensitive 1929 public Constructor<?>[] getDeclaredConstructors() throws SecurityException { 1930 checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true); 1931 return copyConstructors(privateGetDeclaredConstructors(false)); 1932 } 1933 1934 1935 /** 1936 * Returns a {@code Field} object that reflects the specified declared 1937 * field of the class or interface represented by this {@code Class} 1938 * object. The {@code name} parameter is a {@code String} that 1939 * specifies the simple name of the desired field. Note that this method 1940 * will not reflect the {@code length} field of an array class. 1941 * 1942 * @param name the name of the field 1943 * @return the {@code Field} object for the specified field in this 1944 * class 1945 * @throws NoSuchFieldException if a field with the specified name is 1946 * not found. 1947 * @throws NullPointerException if {@code name} is {@code null} 1948 * @throws SecurityException 1949 * If a security manager, <i>s</i>, is present and any of the 1950 * following conditions is met: 1951 * 1952 * <ul> 1953 * 1954 * <li> the caller's class loader is not the same as the 1955 * class loader of this class and invocation of 1956 * {@link SecurityManager#checkPermission 1957 * s.checkPermission} method with 1958 * {@code RuntimePermission("accessDeclaredMembers")} 1959 * denies access to the declared field 1960 * 1961 * <li> the caller's class loader is not the same as or an 1962 * ancestor of the class loader for the current class and 1963 * invocation of {@link SecurityManager#checkPackageAccess 1964 * s.checkPackageAccess()} denies access to the package 1965 * of this class 1966 * 1967 * </ul> 1968 * 1969 * @since JDK1.1 1970 */ 1971 @CallerSensitive 1972 public Field getDeclaredField(String name) 1973 throws NoSuchFieldException, SecurityException { 1974 checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true); 1975 Field field = searchFields(privateGetDeclaredFields(false), name); 1976 if (field == null) { 1977 throw new NoSuchFieldException(name); 1978 } 1979 return field; 1980 } 1981 1982 1983 /** 1984 * Returns a {@code Method} object that reflects the specified 1985 * declared method of the class or interface represented by this 1986 * {@code Class} object. The {@code name} parameter is a 1987 * {@code String} that specifies the simple name of the desired 1988 * method, and the {@code parameterTypes} parameter is an array of 1989 * {@code Class} objects that identify the method's formal parameter 1990 * types, in declared order. If more than one method with the same 1991 * parameter types is declared in a class, and one of these methods has a 1992 * return type that is more specific than any of the others, that method is 1993 * returned; otherwise one of the methods is chosen arbitrarily. If the 1994 * name is "<init>"or "<clinit>" a {@code NoSuchMethodException} 1995 * is raised. 1996 * 1997 * @param name the name of the method 1998 * @param parameterTypes the parameter array 1999 * @return the {@code Method} object for the method of this class 2000 * matching the specified name and parameters 2001 * @throws NoSuchMethodException if a matching method is not found. 2002 * @throws NullPointerException if {@code name} is {@code null} 2003 * @throws SecurityException 2004 * If a security manager, <i>s</i>, is present and any of the 2005 * following conditions is met: 2006 * 2007 * <ul> 2008 * 2009 * <li> the caller's class loader is not the same as the 2010 * class loader of this class and invocation of 2011 * {@link SecurityManager#checkPermission 2012 * s.checkPermission} method with 2013 * {@code RuntimePermission("accessDeclaredMembers")} 2014 * denies access to the declared method 2015 * 2016 * <li> the caller's class loader is not the same as or an 2017 * ancestor of the class loader for the current class and 2018 * invocation of {@link SecurityManager#checkPackageAccess 2019 * s.checkPackageAccess()} denies access to the package 2020 * of this class 2021 * 2022 * </ul> 2023 * 2024 * @since JDK1.1 2025 */ 2026 @CallerSensitive 2027 public Method getDeclaredMethod(String name, Class<?>... parameterTypes) 2028 throws NoSuchMethodException, SecurityException { 2029 checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true); 2030 Method method = searchMethods(privateGetDeclaredMethods(false), name, parameterTypes); 2031 if (method == null) { 2032 throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes)); 2033 } 2034 return method; 2035 } 2036 2037 2038 /** 2039 * Returns a {@code Constructor} object that reflects the specified 2040 * constructor of the class or interface represented by this 2041 * {@code Class} object. The {@code parameterTypes} parameter is 2042 * an array of {@code Class} objects that identify the constructor's 2043 * formal parameter types, in declared order. 2044 * 2045 * If this {@code Class} object represents an inner class 2046 * declared in a non-static context, the formal parameter types 2047 * include the explicit enclosing instance as the first parameter. 2048 * 2049 * @param parameterTypes the parameter array 2050 * @return The {@code Constructor} object for the constructor with the 2051 * specified parameter list 2052 * @throws NoSuchMethodException if a matching method is not found. 2053 * @throws SecurityException 2054 * If a security manager, <i>s</i>, is present and any of the 2055 * following conditions is met: 2056 * 2057 * <ul> 2058 * 2059 * <li> the caller's class loader is not the same as the 2060 * class loader of this class and invocation of 2061 * {@link SecurityManager#checkPermission 2062 * s.checkPermission} method with 2063 * {@code RuntimePermission("accessDeclaredMembers")} 2064 * denies access to the declared constructor 2065 * 2066 * <li> the caller's class loader is not the same as or an 2067 * ancestor of the class loader for the current class and 2068 * invocation of {@link SecurityManager#checkPackageAccess 2069 * s.checkPackageAccess()} denies access to the package 2070 * of this class 2071 * 2072 * </ul> 2073 * 2074 * @since JDK1.1 2075 */ 2076 @CallerSensitive 2077 public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes) 2078 throws NoSuchMethodException, SecurityException { 2079 checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true); 2080 return getConstructor0(parameterTypes, Member.DECLARED); 2081 } 2082 2083 /** 2084 * Finds a resource with a given name. The rules for searching resources 2085 * associated with a given class are implemented by the defining 2086 * {@linkplain ClassLoader class loader} of the class. This method 2087 * delegates to this object's class loader. If this object was loaded by 2088 * the bootstrap class loader, the method delegates to {@link 2089 * ClassLoader#getSystemResourceAsStream}. 2090 * 2091 * <p> Before delegation, an absolute resource name is constructed from the 2092 * given resource name using this algorithm: 2093 * 2094 * <ul> 2095 * 2096 * <li> If the {@code name} begins with a {@code '/'} 2097 * (<tt>'\u002f'</tt>), then the absolute name of the resource is the 2098 * portion of the {@code name} following the {@code '/'}. 2099 * 2100 * <li> Otherwise, the absolute name is of the following form: 2101 * 2102 * <blockquote> 2103 * {@code modified_package_name/name} 2104 * </blockquote> 2105 * 2106 * <p> Where the {@code modified_package_name} is the package name of this 2107 * object with {@code '/'} substituted for {@code '.'} 2108 * (<tt>'\u002e'</tt>). 2109 * 2110 * </ul> 2111 * 2112 * @param name name of the desired resource 2113 * @return A {@link java.io.InputStream} object or {@code null} if 2114 * no resource with this name is found 2115 * @throws NullPointerException If {@code name} is {@code null} 2116 * @since JDK1.1 2117 */ 2118 public InputStream getResourceAsStream(String name) { 2119 name = resolveName(name); 2120 ClassLoader cl = getClassLoader0(); 2121 if (cl==null) { 2122 // A system class. 2123 return ClassLoader.getSystemResourceAsStream(name); 2124 } 2125 return cl.getResourceAsStream(name); 2126 } 2127 2128 /** 2129 * Finds a resource with a given name. The rules for searching resources 2130 * associated with a given class are implemented by the defining 2131 * {@linkplain ClassLoader class loader} of the class. This method 2132 * delegates to this object's class loader. If this object was loaded by 2133 * the bootstrap class loader, the method delegates to {@link 2134 * ClassLoader#getSystemResource}. 2135 * 2136 * <p> Before delegation, an absolute resource name is constructed from the 2137 * given resource name using this algorithm: 2138 * 2139 * <ul> 2140 * 2141 * <li> If the {@code name} begins with a {@code '/'} 2142 * (<tt>'\u002f'</tt>), then the absolute name of the resource is the 2143 * portion of the {@code name} following the {@code '/'}. 2144 * 2145 * <li> Otherwise, the absolute name is of the following form: 2146 * 2147 * <blockquote> 2148 * {@code modified_package_name/name} 2149 * </blockquote> 2150 * 2151 * <p> Where the {@code modified_package_name} is the package name of this 2152 * object with {@code '/'} substituted for {@code '.'} 2153 * (<tt>'\u002e'</tt>). 2154 * 2155 * </ul> 2156 * 2157 * @param name name of the desired resource 2158 * @return A {@link java.net.URL} object or {@code null} if no 2159 * resource with this name is found 2160 * @since JDK1.1 2161 */ 2162 public java.net.URL getResource(String name) { 2163 name = resolveName(name); 2164 ClassLoader cl = getClassLoader0(); 2165 if (cl==null) { 2166 // A system class. 2167 return ClassLoader.getSystemResource(name); 2168 } 2169 return cl.getResource(name); 2170 } 2171 2172 2173 2174 /** protection domain returned when the internal domain is null */ 2175 private static java.security.ProtectionDomain allPermDomain; 2176 2177 2178 /** 2179 * Returns the {@code ProtectionDomain} of this class. If there is a 2180 * security manager installed, this method first calls the security 2181 * manager's {@code checkPermission} method with a 2182 * {@code RuntimePermission("getProtectionDomain")} permission to 2183 * ensure it's ok to get the 2184 * {@code ProtectionDomain}. 2185 * 2186 * @return the ProtectionDomain of this class 2187 * 2188 * @throws SecurityException 2189 * if a security manager exists and its 2190 * {@code checkPermission} method doesn't allow 2191 * getting the ProtectionDomain. 2192 * 2193 * @see java.security.ProtectionDomain 2194 * @see SecurityManager#checkPermission 2195 * @see java.lang.RuntimePermission 2196 * @since 1.2 2197 */ 2198 public java.security.ProtectionDomain getProtectionDomain() { 2199 SecurityManager sm = System.getSecurityManager(); 2200 if (sm != null) { 2201 sm.checkPermission(SecurityConstants.GET_PD_PERMISSION); 2202 } 2203 java.security.ProtectionDomain pd = getProtectionDomain0(); 2204 if (pd == null) { 2205 if (allPermDomain == null) { 2206 java.security.Permissions perms = 2207 new java.security.Permissions(); 2208 perms.add(SecurityConstants.ALL_PERMISSION); 2209 allPermDomain = 2210 new java.security.ProtectionDomain(null, perms); 2211 } 2212 pd = allPermDomain; 2213 } 2214 return pd; 2215 } 2216 2217 2218 /** 2219 * Returns the ProtectionDomain of this class. 2220 */ 2221 private native java.security.ProtectionDomain getProtectionDomain0(); 2222 2223 /* 2224 * Return the Virtual Machine's Class object for the named 2225 * primitive type. 2226 */ 2227 static native Class<?> getPrimitiveClass(String name); 2228 2229 /* 2230 * Check if client is allowed to access members. If access is denied, 2231 * throw a SecurityException. 2232 * 2233 * This method also enforces package access. 2234 * 2235 * <p> Default policy: allow all clients access with normal Java access 2236 * control. 2237 */ 2238 private void checkMemberAccess(int which, Class<?> caller, boolean checkProxyInterfaces) { 2239 final SecurityManager s = System.getSecurityManager(); 2240 if (s != null) { 2241 /* Default policy allows access to all {@link Member#PUBLIC} members, 2242 * as well as access to classes that have the same class loader as the caller. 2243 * In all other cases, it requires RuntimePermission("accessDeclaredMembers") 2244 * permission. 2245 */ 2246 final ClassLoader ccl = ClassLoader.getClassLoader(caller); 2247 final ClassLoader cl = getClassLoader0(); 2248 if (which != Member.PUBLIC) { 2249 if (ccl != cl) { 2250 s.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION); 2251 } 2252 } 2253 this.checkPackageAccess(ccl, checkProxyInterfaces); 2254 } 2255 } 2256 2257 /* 2258 * Checks if a client loaded in ClassLoader ccl is allowed to access this 2259 * class under the current package access policy. If access is denied, 2260 * throw a SecurityException. 2261 */ 2262 private void checkPackageAccess(final ClassLoader ccl, boolean checkProxyInterfaces) { 2263 final SecurityManager s = System.getSecurityManager(); 2264 if (s != null) { 2265 final ClassLoader cl = getClassLoader0(); 2266 2267 if (ReflectUtil.needsPackageAccessCheck(ccl, cl)) { 2268 String name = this.getName(); 2269 int i = name.lastIndexOf('.'); 2270 if (i != -1) { 2271 // skip the package access check on a proxy class in default proxy package 2272 String pkg = name.substring(0, i); 2273 if (!Proxy.isProxyClass(this) || ReflectUtil.isNonPublicProxyClass(this)) { 2274 s.checkPackageAccess(pkg); 2275 } 2276 } 2277 } 2278 // check package access on the proxy interfaces 2279 if (checkProxyInterfaces && Proxy.isProxyClass(this)) { 2280 ReflectUtil.checkProxyPackageAccess(ccl, this.getInterfaces()); 2281 } 2282 } 2283 } 2284 2285 /** 2286 * Add a package name prefix if the name is not absolute Remove leading "/" 2287 * if name is absolute 2288 */ 2289 private String resolveName(String name) { 2290 if (name == null) { 2291 return name; 2292 } 2293 if (!name.startsWith("/")) { 2294 Class<?> c = this; 2295 while (c.isArray()) { 2296 c = c.getComponentType(); 2297 } 2298 String baseName = c.getName(); 2299 int index = baseName.lastIndexOf('.'); 2300 if (index != -1) { 2301 name = baseName.substring(0, index).replace('.', '/') 2302 +"/"+name; 2303 } 2304 } else { 2305 name = name.substring(1); 2306 } 2307 return name; 2308 } 2309 2310 /** 2311 * Atomic operations support. 2312 */ 2313 private static class Atomic { 2314 // initialize Unsafe machinery here, since we need to call Class.class instance method 2315 // and have to avoid calling it in the static initializer of the Class class... 2316 private static final Unsafe unsafe = Unsafe.getUnsafe(); 2317 // offset of Class.reflectionData instance field 2318 private static final long reflectionDataOffset; 2319 // offset of Class.annotationType instance field 2320 private static final long annotationTypeOffset; 2321 2322 static { 2323 Field[] fields = Class.class.getDeclaredFields0(false); // bypass caches 2324 reflectionDataOffset = objectFieldOffset(fields, "reflectionData"); 2325 annotationTypeOffset = objectFieldOffset(fields, "annotationType"); 2326 } 2327 2328 private static long objectFieldOffset(Field[] fields, String fieldName) { 2329 Field field = searchFields(fields, fieldName); 2330 if (field == null) { 2331 throw new Error("No " + fieldName + " field found in java.lang.Class"); 2332 } 2333 return unsafe.objectFieldOffset(field); 2334 } 2335 2336 static <T> boolean casReflectionData(Class<?> clazz, 2337 SoftReference<ReflectionData<T>> oldData, 2338 SoftReference<ReflectionData<T>> newData) { 2339 return unsafe.compareAndSwapObject(clazz, reflectionDataOffset, oldData, newData); 2340 } 2341 2342 static <T> boolean casAnnotationType(Class<?> clazz, 2343 AnnotationType oldType, 2344 AnnotationType newType) { 2345 return unsafe.compareAndSwapObject(clazz, annotationTypeOffset, oldType, newType); 2346 } 2347 } 2348 2349 /** 2350 * Reflection support. 2351 */ 2352 2353 // Caches for certain reflective results 2354 private static boolean useCaches = true; 2355 2356 // reflection data that might get invalidated when JVM TI RedefineClasses() is called 2357 static class ReflectionData<T> { 2358 volatile Field[] declaredFields; 2359 volatile Field[] publicFields; 2360 volatile Method[] declaredMethods; 2361 volatile Method[] publicMethods; 2362 volatile Constructor<T>[] declaredConstructors; 2363 volatile Constructor<T>[] publicConstructors; 2364 // Intermediate results for getFields and getMethods 2365 volatile Field[] declaredPublicFields; 2366 volatile Method[] declaredPublicMethods; 2367 volatile Class<?>[] interfaces; 2368 2369 // Value of classRedefinedCount when we created this ReflectionData instance 2370 final int redefinedCount; 2371 2372 ReflectionData(int redefinedCount) { 2373 this.redefinedCount = redefinedCount; 2374 } 2375 } 2376 2377 private volatile transient SoftReference<ReflectionData<T>> reflectionData; 2378 2379 // Incremented by the VM on each call to JVM TI RedefineClasses() 2380 // that redefines this class or a superclass. 2381 private volatile transient int classRedefinedCount = 0; 2382 2383 // Lazily create and cache ReflectionData 2384 private ReflectionData<T> reflectionData() { 2385 SoftReference<ReflectionData<T>> reflectionData = this.reflectionData; 2386 int classRedefinedCount = this.classRedefinedCount; 2387 ReflectionData<T> rd; 2388 if (useCaches && 2389 reflectionData != null && 2390 (rd = reflectionData.get()) != null && 2391 rd.redefinedCount == classRedefinedCount) { 2392 return rd; 2393 } 2394 // else no SoftReference or cleared SoftReference or stale ReflectionData 2395 // -> create and replace new instance 2396 return newReflectionData(reflectionData, classRedefinedCount); 2397 } 2398 2399 private ReflectionData<T> newReflectionData(SoftReference<ReflectionData<T>> oldReflectionData, 2400 int classRedefinedCount) { 2401 if (!useCaches) return null; 2402 2403 while (true) { 2404 ReflectionData<T> rd = new ReflectionData<>(classRedefinedCount); 2405 // try to CAS it... 2406 if (Atomic.casReflectionData(this, oldReflectionData, new SoftReference<>(rd))) { 2407 return rd; 2408 } 2409 // else retry 2410 oldReflectionData = this.reflectionData; 2411 classRedefinedCount = this.classRedefinedCount; 2412 if (oldReflectionData != null && 2413 (rd = oldReflectionData.get()) != null && 2414 rd.redefinedCount == classRedefinedCount) { 2415 return rd; 2416 } 2417 } 2418 } 2419 2420 // Generic signature handling 2421 private native String getGenericSignature0(); 2422 2423 // Generic info repository; lazily initialized 2424 private volatile transient ClassRepository genericInfo; 2425 2426 // accessor for factory 2427 private GenericsFactory getFactory() { 2428 // create scope and factory 2429 return CoreReflectionFactory.make(this, ClassScope.make(this)); 2430 } 2431 2432 // accessor for generic info repository; 2433 // generic info is lazily initialized 2434 private ClassRepository getGenericInfo() { 2435 ClassRepository genericInfo = this.genericInfo; 2436 if (genericInfo == null) { 2437 String signature = getGenericSignature0(); 2438 if (signature == null) { 2439 genericInfo = ClassRepository.NONE; 2440 } else { 2441 genericInfo = ClassRepository.make(signature, getFactory()); 2442 } 2443 this.genericInfo = genericInfo; 2444 } 2445 return (genericInfo != ClassRepository.NONE) ? genericInfo : null; 2446 } 2447 2448 // Annotations handling 2449 native byte[] getRawAnnotations(); 2450 // Since 1.8 2451 native byte[] getRawTypeAnnotations(); 2452 static byte[] getExecutableTypeAnnotationBytes(Executable ex) { 2453 return getReflectionFactory().getExecutableTypeAnnotationBytes(ex); 2454 } 2455 2456 native ConstantPool getConstantPool(); 2457 2458 // 2459 // 2460 // java.lang.reflect.Field handling 2461 // 2462 // 2463 2464 // Returns an array of "root" fields. These Field objects must NOT 2465 // be propagated to the outside world, but must instead be copied 2466 // via ReflectionFactory.copyField. 2467 private Field[] privateGetDeclaredFields(boolean publicOnly) { 2468 checkInitted(); 2469 Field[] res; 2470 ReflectionData<T> rd = reflectionData(); 2471 if (rd != null) { 2472 res = publicOnly ? rd.declaredPublicFields : rd.declaredFields; 2473 if (res != null) return res; 2474 } 2475 // No cached value available; request value from VM 2476 res = Reflection.filterFields(this, getDeclaredFields0(publicOnly)); 2477 if (rd != null) { 2478 if (publicOnly) { 2479 rd.declaredPublicFields = res; 2480 } else { 2481 rd.declaredFields = res; 2482 } 2483 } 2484 return res; 2485 } 2486 2487 // Returns an array of "root" fields. These Field objects must NOT 2488 // be propagated to the outside world, but must instead be copied 2489 // via ReflectionFactory.copyField. 2490 private Field[] privateGetPublicFields(Set<Class<?>> traversedInterfaces) { 2491 checkInitted(); 2492 Field[] res; 2493 ReflectionData<T> rd = reflectionData(); 2494 if (rd != null) { 2495 res = rd.publicFields; 2496 if (res != null) return res; 2497 } 2498 2499 // No cached value available; compute value recursively. 2500 // Traverse in correct order for getField(). 2501 List<Field> fields = new ArrayList<>(); 2502 if (traversedInterfaces == null) { 2503 traversedInterfaces = new HashSet<>(); 2504 } 2505 2506 // Local fields 2507 Field[] tmp = privateGetDeclaredFields(true); 2508 addAll(fields, tmp); 2509 2510 // Direct superinterfaces, recursively 2511 for (Class<?> c : getInterfaces()) { 2512 if (!traversedInterfaces.contains(c)) { 2513 traversedInterfaces.add(c); 2514 addAll(fields, c.privateGetPublicFields(traversedInterfaces)); 2515 } 2516 } 2517 2518 // Direct superclass, recursively 2519 if (!isInterface()) { 2520 Class<?> c = getSuperclass(); 2521 if (c != null) { 2522 addAll(fields, c.privateGetPublicFields(traversedInterfaces)); 2523 } 2524 } 2525 2526 res = new Field[fields.size()]; 2527 fields.toArray(res); 2528 if (rd != null) { 2529 rd.publicFields = res; 2530 } 2531 return res; 2532 } 2533 2534 private static void addAll(Collection<Field> c, Field[] o) { 2535 for (int i = 0; i < o.length; i++) { 2536 c.add(o[i]); 2537 } 2538 } 2539 2540 2541 // 2542 // 2543 // java.lang.reflect.Constructor handling 2544 // 2545 // 2546 2547 // Returns an array of "root" constructors. These Constructor 2548 // objects must NOT be propagated to the outside world, but must 2549 // instead be copied via ReflectionFactory.copyConstructor. 2550 private Constructor<T>[] privateGetDeclaredConstructors(boolean publicOnly) { 2551 checkInitted(); 2552 Constructor<T>[] res; 2553 ReflectionData<T> rd = reflectionData(); 2554 if (rd != null) { 2555 res = publicOnly ? rd.publicConstructors : rd.declaredConstructors; 2556 if (res != null) return res; 2557 } 2558 // No cached value available; request value from VM 2559 if (isInterface()) { 2560 @SuppressWarnings("unchecked") 2561 Constructor<T>[] temporaryRes = (Constructor<T>[]) new Constructor<?>[0]; 2562 res = temporaryRes; 2563 } else { 2564 res = getDeclaredConstructors0(publicOnly); 2565 } 2566 if (rd != null) { 2567 if (publicOnly) { 2568 rd.publicConstructors = res; 2569 } else { 2570 rd.declaredConstructors = res; 2571 } 2572 } 2573 return res; 2574 } 2575 2576 // 2577 // 2578 // java.lang.reflect.Method handling 2579 // 2580 // 2581 2582 // Returns an array of "root" methods. These Method objects must NOT 2583 // be propagated to the outside world, but must instead be copied 2584 // via ReflectionFactory.copyMethod. 2585 private Method[] privateGetDeclaredMethods(boolean publicOnly) { 2586 checkInitted(); 2587 Method[] res; 2588 ReflectionData<T> rd = reflectionData(); 2589 if (rd != null) { 2590 res = publicOnly ? rd.declaredPublicMethods : rd.declaredMethods; 2591 if (res != null) return res; 2592 } 2593 // No cached value available; request value from VM 2594 res = Reflection.filterMethods(this, getDeclaredMethods0(publicOnly)); 2595 if (rd != null) { 2596 if (publicOnly) { 2597 rd.declaredPublicMethods = res; 2598 } else { 2599 rd.declaredMethods = res; 2600 } 2601 } 2602 return res; 2603 } 2604 2605 static class MethodArray { 2606 private Method[] methods; 2607 private int length; 2608 2609 MethodArray() { 2610 methods = new Method[20]; 2611 length = 0; 2612 } 2613 2614 void add(Method m) { 2615 if (length == methods.length) { 2616 methods = Arrays.copyOf(methods, 2 * methods.length); 2617 } 2618 methods[length++] = m; 2619 } 2620 2621 void addAll(Method[] ma) { 2622 for (int i = 0; i < ma.length; i++) { 2623 add(ma[i]); 2624 } 2625 } 2626 2627 void addAll(MethodArray ma) { 2628 for (int i = 0; i < ma.length(); i++) { 2629 add(ma.get(i)); 2630 } 2631 } 2632 2633 void addIfNotPresent(Method newMethod) { 2634 for (int i = 0; i < length; i++) { 2635 Method m = methods[i]; 2636 if (m == newMethod || (m != null && m.equals(newMethod))) { 2637 return; 2638 } 2639 } 2640 add(newMethod); 2641 } 2642 2643 void addAllIfNotPresent(MethodArray newMethods) { 2644 for (int i = 0; i < newMethods.length(); i++) { 2645 Method m = newMethods.get(i); 2646 if (m != null) { 2647 addIfNotPresent(m); 2648 } 2649 } 2650 } 2651 2652 int length() { 2653 return length; 2654 } 2655 2656 Method get(int i) { 2657 return methods[i]; 2658 } 2659 2660 void removeByNameAndSignature(Method toRemove) { 2661 for (int i = 0; i < length; i++) { 2662 Method m = methods[i]; 2663 if (m != null && 2664 m.getReturnType() == toRemove.getReturnType() && 2665 m.getName() == toRemove.getName() && 2666 arrayContentsEq(m.getParameterTypes(), 2667 toRemove.getParameterTypes())) { 2668 methods[i] = null; 2669 } 2670 } 2671 } 2672 2673 void compactAndTrim() { 2674 int newPos = 0; 2675 // Get rid of null slots 2676 for (int pos = 0; pos < length; pos++) { 2677 Method m = methods[pos]; 2678 if (m != null) { 2679 if (pos != newPos) { 2680 methods[newPos] = m; 2681 } 2682 newPos++; 2683 } 2684 } 2685 if (newPos != methods.length) { 2686 methods = Arrays.copyOf(methods, newPos); 2687 } 2688 } 2689 2690 Method[] getArray() { 2691 return methods; 2692 } 2693 } 2694 2695 2696 // Returns an array of "root" methods. These Method objects must NOT 2697 // be propagated to the outside world, but must instead be copied 2698 // via ReflectionFactory.copyMethod. 2699 private Method[] privateGetPublicMethods() { 2700 checkInitted(); 2701 Method[] res; 2702 ReflectionData<T> rd = reflectionData(); 2703 if (rd != null) { 2704 res = rd.publicMethods; 2705 if (res != null) return res; 2706 } 2707 2708 // No cached value available; compute value recursively. 2709 // Start by fetching public declared methods 2710 MethodArray methods = new MethodArray(); 2711 { 2712 Method[] tmp = privateGetDeclaredMethods(true); 2713 methods.addAll(tmp); 2714 } 2715 // Now recur over superclass and direct superinterfaces. 2716 // Go over superinterfaces first so we can more easily filter 2717 // out concrete implementations inherited from superclasses at 2718 // the end. 2719 MethodArray inheritedMethods = new MethodArray(); 2720 Class<?>[] interfaces = getInterfaces(); 2721 for (int i = 0; i < interfaces.length; i++) { 2722 inheritedMethods.addAll(interfaces[i].privateGetPublicMethods()); 2723 } 2724 if (!isInterface()) { 2725 Class<?> c = getSuperclass(); 2726 if (c != null) { 2727 MethodArray supers = new MethodArray(); 2728 supers.addAll(c.privateGetPublicMethods()); 2729 // Filter out concrete implementations of any 2730 // interface methods 2731 for (int i = 0; i < supers.length(); i++) { 2732 Method m = supers.get(i); 2733 if (m != null && !Modifier.isAbstract(m.getModifiers())) { 2734 inheritedMethods.removeByNameAndSignature(m); 2735 } 2736 } 2737 // Insert superclass's inherited methods before 2738 // superinterfaces' to satisfy getMethod's search 2739 // order 2740 supers.addAll(inheritedMethods); 2741 inheritedMethods = supers; 2742 } 2743 } 2744 // Filter out all local methods from inherited ones 2745 for (int i = 0; i < methods.length(); i++) { 2746 Method m = methods.get(i); 2747 inheritedMethods.removeByNameAndSignature(m); 2748 } 2749 methods.addAllIfNotPresent(inheritedMethods); 2750 methods.compactAndTrim(); 2751 res = methods.getArray(); 2752 if (rd != null) { 2753 rd.publicMethods = res; 2754 } 2755 return res; 2756 } 2757 2758 2759 // 2760 // Helpers for fetchers of one field, method, or constructor 2761 // 2762 2763 private static Field searchFields(Field[] fields, String name) { 2764 String internedName = name.intern(); 2765 for (int i = 0; i < fields.length; i++) { 2766 if (fields[i].getName() == internedName) { 2767 return getReflectionFactory().copyField(fields[i]); 2768 } 2769 } 2770 return null; 2771 } 2772 2773 private Field getField0(String name) throws NoSuchFieldException { 2774 // Note: the intent is that the search algorithm this routine 2775 // uses be equivalent to the ordering imposed by 2776 // privateGetPublicFields(). It fetches only the declared 2777 // public fields for each class, however, to reduce the number 2778 // of Field objects which have to be created for the common 2779 // case where the field being requested is declared in the 2780 // class which is being queried. 2781 Field res; 2782 // Search declared public fields 2783 if ((res = searchFields(privateGetDeclaredFields(true), name)) != null) { 2784 return res; 2785 } 2786 // Direct superinterfaces, recursively 2787 Class<?>[] interfaces = getInterfaces(); 2788 for (int i = 0; i < interfaces.length; i++) { 2789 Class<?> c = interfaces[i]; 2790 if ((res = c.getField0(name)) != null) { 2791 return res; 2792 } 2793 } 2794 // Direct superclass, recursively 2795 if (!isInterface()) { 2796 Class<?> c = getSuperclass(); 2797 if (c != null) { 2798 if ((res = c.getField0(name)) != null) { 2799 return res; 2800 } 2801 } 2802 } 2803 return null; 2804 } 2805 2806 private static Method searchMethods(Method[] methods, 2807 String name, 2808 Class<?>[] parameterTypes) 2809 { 2810 Method res = null; 2811 String internedName = name.intern(); 2812 for (int i = 0; i < methods.length; i++) { 2813 Method m = methods[i]; 2814 if (m.getName() == internedName 2815 && arrayContentsEq(parameterTypes, m.getParameterTypes()) 2816 && (res == null 2817 || res.getReturnType().isAssignableFrom(m.getReturnType()))) 2818 res = m; 2819 } 2820 2821 return (res == null ? res : getReflectionFactory().copyMethod(res)); 2822 } 2823 2824 2825 private Method getMethod0(String name, Class<?>[] parameterTypes) { 2826 // Note: the intent is that the search algorithm this routine 2827 // uses be equivalent to the ordering imposed by 2828 // privateGetPublicMethods(). It fetches only the declared 2829 // public methods for each class, however, to reduce the 2830 // number of Method objects which have to be created for the 2831 // common case where the method being requested is declared in 2832 // the class which is being queried. 2833 Method res; 2834 // Search declared public methods 2835 if ((res = searchMethods(privateGetDeclaredMethods(true), 2836 name, 2837 parameterTypes)) != null) { 2838 return res; 2839 } 2840 // Search superclass's methods 2841 if (!isInterface()) { 2842 Class<? super T> c = getSuperclass(); 2843 if (c != null) { 2844 if ((res = c.getMethod0(name, parameterTypes)) != null) { 2845 return res; 2846 } 2847 } 2848 } 2849 // Search superinterfaces' methods 2850 Class<?>[] interfaces = getInterfaces(); 2851 for (int i = 0; i < interfaces.length; i++) { 2852 Class<?> c = interfaces[i]; 2853 if ((res = c.getMethod0(name, parameterTypes)) != null) { 2854 return res; 2855 } 2856 } 2857 // Not found 2858 return null; 2859 } 2860 2861 private Constructor<T> getConstructor0(Class<?>[] parameterTypes, 2862 int which) throws NoSuchMethodException 2863 { 2864 Constructor<T>[] constructors = privateGetDeclaredConstructors((which == Member.PUBLIC)); 2865 for (Constructor<T> constructor : constructors) { 2866 if (arrayContentsEq(parameterTypes, 2867 constructor.getParameterTypes())) { 2868 return getReflectionFactory().copyConstructor(constructor); 2869 } 2870 } 2871 throw new NoSuchMethodException(getName() + ".<init>" + argumentTypesToString(parameterTypes)); 2872 } 2873 2874 // 2875 // Other helpers and base implementation 2876 // 2877 2878 private static boolean arrayContentsEq(Object[] a1, Object[] a2) { 2879 if (a1 == null) { 2880 return a2 == null || a2.length == 0; 2881 } 2882 2883 if (a2 == null) { 2884 return a1.length == 0; 2885 } 2886 2887 if (a1.length != a2.length) { 2888 return false; 2889 } 2890 2891 for (int i = 0; i < a1.length; i++) { 2892 if (a1[i] != a2[i]) { 2893 return false; 2894 } 2895 } 2896 2897 return true; 2898 } 2899 2900 private static Field[] copyFields(Field[] arg) { 2901 Field[] out = new Field[arg.length]; 2902 ReflectionFactory fact = getReflectionFactory(); 2903 for (int i = 0; i < arg.length; i++) { 2904 out[i] = fact.copyField(arg[i]); 2905 } 2906 return out; 2907 } 2908 2909 private static Method[] copyMethods(Method[] arg) { 2910 Method[] out = new Method[arg.length]; 2911 ReflectionFactory fact = getReflectionFactory(); 2912 for (int i = 0; i < arg.length; i++) { 2913 out[i] = fact.copyMethod(arg[i]); 2914 } 2915 return out; 2916 } 2917 2918 private static <U> Constructor<U>[] copyConstructors(Constructor<U>[] arg) { 2919 Constructor<U>[] out = arg.clone(); 2920 ReflectionFactory fact = getReflectionFactory(); 2921 for (int i = 0; i < out.length; i++) { 2922 out[i] = fact.copyConstructor(out[i]); 2923 } 2924 return out; 2925 } 2926 2927 private native Field[] getDeclaredFields0(boolean publicOnly); 2928 private native Method[] getDeclaredMethods0(boolean publicOnly); 2929 private native Constructor<T>[] getDeclaredConstructors0(boolean publicOnly); 2930 private native Class<?>[] getDeclaredClasses0(); 2931 2932 private static String argumentTypesToString(Class<?>[] argTypes) { 2933 StringBuilder buf = new StringBuilder(); 2934 buf.append("("); 2935 if (argTypes != null) { 2936 for (int i = 0; i < argTypes.length; i++) { 2937 if (i > 0) { 2938 buf.append(", "); 2939 } 2940 Class<?> c = argTypes[i]; 2941 buf.append((c == null) ? "null" : c.getName()); 2942 } 2943 } 2944 buf.append(")"); 2945 return buf.toString(); 2946 } 2947 2948 /** use serialVersionUID from JDK 1.1 for interoperability */ 2949 private static final long serialVersionUID = 3206093459760846163L; 2950 2951 2952 /** 2953 * Class Class is special cased within the Serialization Stream Protocol. 2954 * 2955 * A Class instance is written initially into an ObjectOutputStream in the 2956 * following format: 2957 * <pre> 2958 * {@code TC_CLASS} ClassDescriptor 2959 * A ClassDescriptor is a special cased serialization of 2960 * a {@code java.io.ObjectStreamClass} instance. 2961 * </pre> 2962 * A new handle is generated for the initial time the class descriptor 2963 * is written into the stream. Future references to the class descriptor 2964 * are written as references to the initial class descriptor instance. 2965 * 2966 * @see java.io.ObjectStreamClass 2967 */ 2968 private static final ObjectStreamField[] serialPersistentFields = 2969 new ObjectStreamField[0]; 2970 2971 2972 /** 2973 * Returns the assertion status that would be assigned to this 2974 * class if it were to be initialized at the time this method is invoked. 2975 * If this class has had its assertion status set, the most recent 2976 * setting will be returned; otherwise, if any package default assertion 2977 * status pertains to this class, the most recent setting for the most 2978 * specific pertinent package default assertion status is returned; 2979 * otherwise, if this class is not a system class (i.e., it has a 2980 * class loader) its class loader's default assertion status is returned; 2981 * otherwise, the system class default assertion status is returned. 2982 * <p> 2983 * Few programmers will have any need for this method; it is provided 2984 * for the benefit of the JRE itself. (It allows a class to determine at 2985 * the time that it is initialized whether assertions should be enabled.) 2986 * Note that this method is not guaranteed to return the actual 2987 * assertion status that was (or will be) associated with the specified 2988 * class when it was (or will be) initialized. 2989 * 2990 * @return the desired assertion status of the specified class. 2991 * @see java.lang.ClassLoader#setClassAssertionStatus 2992 * @see java.lang.ClassLoader#setPackageAssertionStatus 2993 * @see java.lang.ClassLoader#setDefaultAssertionStatus 2994 * @since 1.4 2995 */ 2996 public boolean desiredAssertionStatus() { 2997 ClassLoader loader = getClassLoader(); 2998 // If the loader is null this is a system class, so ask the VM 2999 if (loader == null) 3000 return desiredAssertionStatus0(this); 3001 3002 // If the classloader has been initialized with the assertion 3003 // directives, ask it. Otherwise, ask the VM. 3004 synchronized(loader.assertionLock) { 3005 if (loader.classAssertionStatus != null) { 3006 return loader.desiredAssertionStatus(getName()); 3007 } 3008 } 3009 return desiredAssertionStatus0(this); 3010 } 3011 3012 // Retrieves the desired assertion status of this class from the VM 3013 private static native boolean desiredAssertionStatus0(Class<?> clazz); 3014 3015 /** 3016 * Returns true if and only if this class was declared as an enum in the 3017 * source code. 3018 * 3019 * @return true if and only if this class was declared as an enum in the 3020 * source code 3021 * @since 1.5 3022 */ 3023 public boolean isEnum() { 3024 // An enum must both directly extend java.lang.Enum and have 3025 // the ENUM bit set; classes for specialized enum constants 3026 // don't do the former. 3027 return (this.getModifiers() & ENUM) != 0 && 3028 this.getSuperclass() == java.lang.Enum.class; 3029 } 3030 3031 // Fetches the factory for reflective objects 3032 private static ReflectionFactory getReflectionFactory() { 3033 if (reflectionFactory == null) { 3034 reflectionFactory = 3035 java.security.AccessController.doPrivileged 3036 (new sun.reflect.ReflectionFactory.GetReflectionFactoryAction()); 3037 } 3038 return reflectionFactory; 3039 } 3040 private static ReflectionFactory reflectionFactory; 3041 3042 // To be able to query system properties as soon as they're available 3043 private static boolean initted = false; 3044 private static void checkInitted() { 3045 if (initted) return; 3046 AccessController.doPrivileged(new PrivilegedAction<Void>() { 3047 public Void run() { 3048 // Tests to ensure the system properties table is fully 3049 // initialized. This is needed because reflection code is 3050 // called very early in the initialization process (before 3051 // command-line arguments have been parsed and therefore 3052 // these user-settable properties installed.) We assume that 3053 // if System.out is non-null then the System class has been 3054 // fully initialized and that the bulk of the startup code 3055 // has been run. 3056 3057 if (System.out == null) { 3058 // java.lang.System not yet fully initialized 3059 return null; 3060 } 3061 3062 // Doesn't use Boolean.getBoolean to avoid class init. 3063 String val = 3064 System.getProperty("sun.reflect.noCaches"); 3065 if (val != null && val.equals("true")) { 3066 useCaches = false; 3067 } 3068 3069 initted = true; 3070 return null; 3071 } 3072 }); 3073 } 3074 3075 /** 3076 * Returns the elements of this enum class or null if this 3077 * Class object does not represent an enum type. 3078 * 3079 * @return an array containing the values comprising the enum class 3080 * represented by this Class object in the order they're 3081 * declared, or null if this Class object does not 3082 * represent an enum type 3083 * @since 1.5 3084 */ 3085 public T[] getEnumConstants() { 3086 T[] values = getEnumConstantsShared(); 3087 return (values != null) ? values.clone() : null; 3088 } 3089 3090 /** 3091 * Returns the elements of this enum class or null if this 3092 * Class object does not represent an enum type; 3093 * identical to getEnumConstants except that the result is 3094 * uncloned, cached, and shared by all callers. 3095 */ 3096 T[] getEnumConstantsShared() { 3097 if (enumConstants == null) { 3098 if (!isEnum()) return null; 3099 try { 3100 final Method values = getMethod("values"); 3101 java.security.AccessController.doPrivileged( 3102 new java.security.PrivilegedAction<Void>() { 3103 public Void run() { 3104 values.setAccessible(true); 3105 return null; 3106 } 3107 }); 3108 @SuppressWarnings("unchecked") 3109 T[] temporaryConstants = (T[])values.invoke(null); 3110 enumConstants = temporaryConstants; 3111 } 3112 // These can happen when users concoct enum-like classes 3113 // that don't comply with the enum spec. 3114 catch (InvocationTargetException | NoSuchMethodException | 3115 IllegalAccessException ex) { return null; } 3116 } 3117 return enumConstants; 3118 } 3119 private volatile transient T[] enumConstants = null; 3120 3121 /** 3122 * Returns a map from simple name to enum constant. This package-private 3123 * method is used internally by Enum to implement 3124 * {@code public static <T extends Enum<T>> T valueOf(Class<T>, String)} 3125 * efficiently. Note that the map is returned by this method is 3126 * created lazily on first use. Typically it won't ever get created. 3127 */ 3128 Map<String, T> enumConstantDirectory() { 3129 if (enumConstantDirectory == null) { 3130 T[] universe = getEnumConstantsShared(); 3131 if (universe == null) 3132 throw new IllegalArgumentException( 3133 getName() + " is not an enum type"); 3134 Map<String, T> m = new HashMap<>(2 * universe.length); 3135 for (T constant : universe) 3136 m.put(((Enum<?>)constant).name(), constant); 3137 enumConstantDirectory = m; 3138 } 3139 return enumConstantDirectory; 3140 } 3141 private volatile transient Map<String, T> enumConstantDirectory = null; 3142 3143 /** 3144 * Casts an object to the class or interface represented 3145 * by this {@code Class} object. 3146 * 3147 * @param obj the object to be cast 3148 * @return the object after casting, or null if obj is null 3149 * 3150 * @throws ClassCastException if the object is not 3151 * null and is not assignable to the type T. 3152 * 3153 * @since 1.5 3154 */ 3155 @SuppressWarnings("unchecked") 3156 public T cast(Object obj) { 3157 if (obj != null && !isInstance(obj)) 3158 throw new ClassCastException(cannotCastMsg(obj)); 3159 return (T) obj; 3160 } 3161 3162 private String cannotCastMsg(Object obj) { 3163 return "Cannot cast " + obj.getClass().getName() + " to " + getName(); 3164 } 3165 3166 /** 3167 * Casts this {@code Class} object to represent a subclass of the class 3168 * represented by the specified class object. Checks that the cast 3169 * is valid, and throws a {@code ClassCastException} if it is not. If 3170 * this method succeeds, it always returns a reference to this class object. 3171 * 3172 * <p>This method is useful when a client needs to "narrow" the type of 3173 * a {@code Class} object to pass it to an API that restricts the 3174 * {@code Class} objects that it is willing to accept. A cast would 3175 * generate a compile-time warning, as the correctness of the cast 3176 * could not be checked at runtime (because generic types are implemented 3177 * by erasure). 3178 * 3179 * @param <U> the type to cast this class object to 3180 * @param clazz the class of the type to cast this class object to 3181 * @return this {@code Class} object, cast to represent a subclass of 3182 * the specified class object. 3183 * @throws ClassCastException if this {@code Class} object does not 3184 * represent a subclass of the specified class (here "subclass" includes 3185 * the class itself). 3186 * @since 1.5 3187 */ 3188 @SuppressWarnings("unchecked") 3189 public <U> Class<? extends U> asSubclass(Class<U> clazz) { 3190 if (clazz.isAssignableFrom(this)) 3191 return (Class<? extends U>) this; 3192 else 3193 throw new ClassCastException(this.toString()); 3194 } 3195 3196 /** 3197 * @throws NullPointerException {@inheritDoc} 3198 * @since 1.5 3199 */ 3200 @SuppressWarnings("unchecked") 3201 public <A extends Annotation> A getAnnotation(Class<A> annotationClass) { 3202 Objects.requireNonNull(annotationClass); 3203 3204 initAnnotationsIfNecessary(); 3205 return (A) annotations.get(annotationClass); 3206 } 3207 3208 /** 3209 * {@inheritDoc} 3210 * @throws NullPointerException {@inheritDoc} 3211 * @since 1.5 3212 */ 3213 @Override 3214 public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) { 3215 return GenericDeclaration.super.isAnnotationPresent(annotationClass); 3216 } 3217 3218 /** 3219 * @throws NullPointerException {@inheritDoc} 3220 * @since 1.8 3221 */ 3222 @Override 3223 public <A extends Annotation> A[] getAnnotationsByType(Class<A> annotationClass) { 3224 Objects.requireNonNull(annotationClass); 3225 3226 initAnnotationsIfNecessary(); 3227 return AnnotationSupport.getMultipleAnnotations(annotations, annotationClass); 3228 } 3229 3230 /** 3231 * @since 1.5 3232 */ 3233 public Annotation[] getAnnotations() { 3234 initAnnotationsIfNecessary(); 3235 return AnnotationParser.toArray(annotations); 3236 } 3237 3238 /** 3239 * @throws NullPointerException {@inheritDoc} 3240 * @since 1.8 3241 */ 3242 @Override 3243 @SuppressWarnings("unchecked") 3244 public <A extends Annotation> A getDeclaredAnnotation(Class<A> annotationClass) { 3245 Objects.requireNonNull(annotationClass); 3246 3247 initAnnotationsIfNecessary(); 3248 return (A) declaredAnnotations.get(annotationClass); 3249 } 3250 3251 /** 3252 * @throws NullPointerException {@inheritDoc} 3253 * @since 1.8 3254 */ 3255 @Override 3256 public <A extends Annotation> A[] getDeclaredAnnotationsByType(Class<A> annotationClass) { 3257 Objects.requireNonNull(annotationClass); 3258 3259 initAnnotationsIfNecessary(); 3260 return AnnotationSupport.getMultipleAnnotations(declaredAnnotations, annotationClass); 3261 } 3262 3263 /** 3264 * @since 1.5 3265 */ 3266 public Annotation[] getDeclaredAnnotations() { 3267 initAnnotationsIfNecessary(); 3268 return AnnotationParser.toArray(declaredAnnotations); 3269 } 3270 3271 // Annotations cache 3272 private transient Map<Class<? extends Annotation>, Annotation> annotations; 3273 private transient Map<Class<? extends Annotation>, Annotation> declaredAnnotations; 3274 // Value of classRedefinedCount when we last cleared the cached annotations and declaredAnnotations fields 3275 private transient int lastAnnotationsRedefinedCount = 0; 3276 3277 // Clears cached values that might possibly have been obsoleted by 3278 // a class redefinition. 3279 private void clearAnnotationCachesOnClassRedefinition() { 3280 if (lastAnnotationsRedefinedCount != classRedefinedCount) { 3281 annotations = declaredAnnotations = null; 3282 lastAnnotationsRedefinedCount = classRedefinedCount; 3283 } 3284 } 3285 3286 private synchronized void initAnnotationsIfNecessary() { 3287 clearAnnotationCachesOnClassRedefinition(); 3288 if (annotations != null) 3289 return; 3290 declaredAnnotations = AnnotationParser.parseAnnotations( 3291 getRawAnnotations(), getConstantPool(), this); 3292 Class<?> superClass = getSuperclass(); 3293 if (superClass == null) { 3294 annotations = declaredAnnotations; 3295 } else { 3296 annotations = new HashMap<>(); 3297 superClass.initAnnotationsIfNecessary(); 3298 for (Map.Entry<Class<? extends Annotation>, Annotation> e : superClass.annotations.entrySet()) { 3299 Class<? extends Annotation> annotationClass = e.getKey(); 3300 if (AnnotationType.getInstance(annotationClass).isInherited()) 3301 annotations.put(annotationClass, e.getValue()); 3302 } 3303 annotations.putAll(declaredAnnotations); 3304 } 3305 } 3306 3307 // Annotation types cache their internal (AnnotationType) form 3308 3309 @SuppressWarnings("UnusedDeclaration") 3310 private volatile transient AnnotationType annotationType; 3311 3312 boolean casAnnotationType(AnnotationType oldType, AnnotationType newType) { 3313 return Atomic.casAnnotationType(this, oldType, newType); 3314 } 3315 3316 AnnotationType getAnnotationType() { 3317 return annotationType; 3318 } 3319 3320 /* Backing store of user-defined values pertaining to this class. 3321 * Maintained by the ClassValue class. 3322 */ 3323 transient ClassValue.ClassValueMap classValueMap; 3324 3325 /** 3326 * Returns an AnnotatedType object that represents the use of a type to specify 3327 * the superclass of the entity represented by this Class. (The <em>use</em> of type 3328 * Foo to specify the superclass in '... extends Foo' is distinct from the 3329 * <em>declaration</em> of type Foo.) 3330 * 3331 * If this Class represents a class type whose declaration does not explicitly 3332 * indicate an annotated superclass, the return value is null. 3333 * 3334 * If this Class represents either the Object class, an interface type, an 3335 * array type, a primitive type, or void, the return value is null. 3336 * 3337 * @return an object representing the superclass 3338 * @since 1.8 3339 */ 3340 public AnnotatedType getAnnotatedSuperclass() { 3341 return TypeAnnotationParser.buildAnnotatedSuperclass(getRawTypeAnnotations(), getConstantPool(), this); 3342 } 3343 3344 /** 3345 * Returns an array of AnnotatedType objects that represent the use of types to 3346 * specify superinterfaces of the entity represented by this Class. (The <em>use</em> 3347 * of type Foo to specify a superinterface in '... implements Foo' is 3348 * distinct from the <em>declaration</em> of type Foo.) 3349 * 3350 * If this Class represents a class, the return value is an array 3351 * containing objects representing the uses of interface types to specify 3352 * interfaces implemented by the class. The order of the objects in the 3353 * array corresponds to the order of the interface types used in the 3354 * 'implements' clause of the declaration of this Class. 3355 * 3356 * If this Class represents an interface, the return value is an array 3357 * containing objects representing the uses of interface types to specify 3358 * interfaces directly extended by the interface. The order of the objects in 3359 * the array corresponds to the order of the interface types used in the 3360 * 'extends' clause of the declaration of this Class. 3361 * 3362 * If this Class represents a class or interface whose declaration does not 3363 * explicitly indicate any annotated superinterfaces, the return value is an 3364 * array of length 0. 3365 * 3366 * If this Class represents either the Object class, an array type, a 3367 * primitive type, or void, the return value is an array of length 0. 3368 * 3369 * @return an array representing the superinterfaces 3370 * @since 1.8 3371 */ 3372 public AnnotatedType[] getAnnotatedInterfaces() { 3373 return TypeAnnotationParser.buildAnnotatedInterfaces(getRawTypeAnnotations(), getConstantPool(), this); 3374 } 3375 }