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