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