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 * Return the Virtual Machine's Class object for the named 2217 * primitive type. 2218 */ 2219 static native Class<?> getPrimitiveClass(String name); 2220 2221 private static boolean isCheckMemberAccessOverridden(SecurityManager smgr) { 2222 if (smgr.getClass() == SecurityManager.class) return false; 2223 2224 Class<?>[] paramTypes = new Class<?>[] {Class.class, int.class}; 2225 return smgr.getClass().getMethod0("checkMemberAccess", paramTypes). 2226 getDeclaringClass() != SecurityManager.class; 2227 } 2228 2229 /* 2230 * Check if client is allowed to access members. If access is denied, 2231 * throw a SecurityException. 2232 * 2233 * <p> Default policy: allow all clients access with normal Java access 2234 * control. 2235 */ 2236 private void checkMemberAccess(int which, Class<?> caller, boolean checkProxyInterfaces) { 2237 final SecurityManager s = System.getSecurityManager(); 2238 if (s != null) { 2239 final ClassLoader ccl = ClassLoader.getClassLoader(caller); 2240 final ClassLoader cl = getClassLoader0(); 2241 if (!isCheckMemberAccessOverridden(s)) { 2242 // Inlined SecurityManager.checkMemberAccess 2243 if (which != Member.PUBLIC) { 2244 if (ccl != cl) { 2245 s.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION); 2246 } 2247 } 2248 } else { 2249 // Don't refactor; otherwise break the stack depth for 2250 // checkMemberAccess of subclasses of SecurityManager as specified. 2251 s.checkMemberAccess(this, which); 2252 } 2253 2254 2255 if (ReflectUtil.needsPackageAccessCheck(ccl, cl)) { 2256 String name = this.getName(); 2257 int i = name.lastIndexOf('.'); 2258 if (i != -1) { 2259 // skip the package access check on a proxy class in default proxy package 2260 String pkg = name.substring(0, i); 2261 if (!Proxy.isProxyClass(this) || !pkg.equals(ReflectUtil.PROXY_PACKAGE)) { 2262 s.checkPackageAccess(pkg); 2263 } 2264 } 2265 } 2266 // check package access on the proxy interfaces 2267 if (checkProxyInterfaces && Proxy.isProxyClass(this)) { 2268 ReflectUtil.checkProxyPackageAccess(ccl, this.getInterfaces()); 2269 } 2270 } 2271 } 2272 2273 /** 2274 * Add a package name prefix if the name is not absolute Remove leading "/" 2275 * if name is absolute 2276 */ 2277 private String resolveName(String name) { 2278 if (name == null) { 2279 return name; 2280 } 2281 if (!name.startsWith("/")) { 2282 Class<?> c = this; 2283 while (c.isArray()) { 2284 c = c.getComponentType(); 2285 } 2286 String baseName = c.getName(); 2287 int index = baseName.lastIndexOf('.'); 2288 if (index != -1) { 2289 name = baseName.substring(0, index).replace('.', '/') 2290 +"/"+name; 2291 } 2292 } else { 2293 name = name.substring(1); 2294 } 2295 return name; 2296 } 2297 2298 /** 2299 * Reflection support. 2300 */ 2301 2302 // Caches for certain reflective results 2303 private static boolean useCaches = true; 2304 2305 // reflection data that might get invalidated when JVM TI RedefineClasses() is called 2306 static class ReflectionData<T> { 2307 volatile Field[] declaredFields; 2308 volatile Field[] publicFields; 2309 volatile Method[] declaredMethods; 2310 volatile Method[] publicMethods; 2311 volatile Constructor<T>[] declaredConstructors; 2312 volatile Constructor<T>[] publicConstructors; 2313 // Intermediate results for getFields and getMethods 2314 volatile Field[] declaredPublicFields; 2315 volatile Method[] declaredPublicMethods; 2316 // Value of classRedefinedCount when we created this ReflectionData instance 2317 final int redefinedCount; 2318 2319 ReflectionData(int redefinedCount) { 2320 this.redefinedCount = redefinedCount; 2321 } 2322 2323 // initialize Unsafe machinery here, since we need to call Class.class instance method 2324 // and have to avoid calling it in the static initializer of the Class class... 2325 private static final Unsafe unsafe; 2326 // offset of Class.reflectionData instance field 2327 private static final long reflectionDataOffset; 2328 2329 static { 2330 unsafe = Unsafe.getUnsafe(); 2331 // bypass caches 2332 Field reflectionDataField = searchFields(Class.class.getDeclaredFields0(false), 2333 "reflectionData"); 2334 if (reflectionDataField == null) { 2335 throw new Error("No reflectionData field found in java.lang.Class"); 2336 } 2337 reflectionDataOffset = unsafe.objectFieldOffset(reflectionDataField); 2338 } 2339 2340 static <T> boolean compareAndSwap(Class<?> clazz, 2341 SoftReference<ReflectionData<T>> oldData, 2342 SoftReference<ReflectionData<T>> newData) { 2343 return unsafe.compareAndSwapObject(clazz, reflectionDataOffset, oldData, newData); 2344 } 2345 } 2346 2347 private volatile transient SoftReference<ReflectionData<T>> reflectionData; 2348 2349 // Incremented by the VM on each call to JVM TI RedefineClasses() 2350 // that redefines this class or a superclass. 2351 private volatile transient int classRedefinedCount = 0; 2352 2353 // Lazily create and cache ReflectionData 2354 private ReflectionData<T> reflectionData() { 2355 SoftReference<ReflectionData<T>> reflectionData = this.reflectionData; 2356 int classRedefinedCount = this.classRedefinedCount; 2357 ReflectionData<T> rd; 2358 if (useCaches && 2359 reflectionData != null && 2360 (rd = reflectionData.get()) != null && 2361 rd.redefinedCount == classRedefinedCount) { 2362 return rd; 2363 } 2364 // else no SoftReference or cleared SoftReference or stale ReflectionData 2365 // -> create and replace new instance 2366 return newReflectionData(reflectionData, classRedefinedCount); 2367 } 2368 2369 private ReflectionData<T> newReflectionData(SoftReference<ReflectionData<T>> oldReflectionData, 2370 int classRedefinedCount) { 2371 if (!useCaches) return null; 2372 2373 while (true) { 2374 ReflectionData<T> rd = new ReflectionData<>(classRedefinedCount); 2375 // try to CAS it... 2376 if (ReflectionData.compareAndSwap(this, oldReflectionData, new SoftReference<>(rd))) { 2377 return rd; 2378 } 2379 // else retry 2380 oldReflectionData = this.reflectionData; 2381 classRedefinedCount = this.classRedefinedCount; 2382 if (oldReflectionData != null && 2383 (rd = oldReflectionData.get()) != null && 2384 rd.redefinedCount == classRedefinedCount) { 2385 return rd; 2386 } 2387 } 2388 } 2389 2390 // Generic signature handling 2391 private native String getGenericSignature(); 2392 2393 // Generic info repository; lazily initialized 2394 private transient ClassRepository genericInfo; 2395 2396 // accessor for factory 2397 private GenericsFactory getFactory() { 2398 // create scope and factory 2399 return CoreReflectionFactory.make(this, ClassScope.make(this)); 2400 } 2401 2402 // accessor for generic info repository 2403 private ClassRepository getGenericInfo() { 2404 // lazily initialize repository if necessary 2405 if (genericInfo == null) { 2406 // create and cache generic info repository 2407 genericInfo = ClassRepository.make(getGenericSignature(), 2408 getFactory()); 2409 } 2410 return genericInfo; //return cached repository 2411 } 2412 2413 // Annotations handling 2414 private native byte[] getRawAnnotations(); 2415 // Since 1.8 2416 native byte[] getRawTypeAnnotations(); 2417 static byte[] getExecutableTypeAnnotationBytes(Executable ex) { 2418 return getReflectionFactory().getExecutableTypeAnnotationBytes(ex); 2419 } 2420 2421 native ConstantPool getConstantPool(); 2422 2423 // 2424 // 2425 // java.lang.reflect.Field handling 2426 // 2427 // 2428 2429 // Returns an array of "root" fields. These Field objects must NOT 2430 // be propagated to the outside world, but must instead be copied 2431 // via ReflectionFactory.copyField. 2432 private Field[] privateGetDeclaredFields(boolean publicOnly) { 2433 checkInitted(); 2434 Field[] res; 2435 ReflectionData<T> rd = reflectionData(); 2436 if (rd != null) { 2437 res = publicOnly ? rd.declaredPublicFields : rd.declaredFields; 2438 if (res != null) return res; 2439 } 2440 // No cached value available; request value from VM 2441 res = Reflection.filterFields(this, getDeclaredFields0(publicOnly)); 2442 if (rd != null) { 2443 if (publicOnly) { 2444 rd.declaredPublicFields = res; 2445 } else { 2446 rd.declaredFields = res; 2447 } 2448 } 2449 return res; 2450 } 2451 2452 // Returns an array of "root" fields. These Field objects must NOT 2453 // be propagated to the outside world, but must instead be copied 2454 // via ReflectionFactory.copyField. 2455 private Field[] privateGetPublicFields(Set<Class<?>> traversedInterfaces) { 2456 checkInitted(); 2457 Field[] res; 2458 ReflectionData<T> rd = reflectionData(); 2459 if (rd != null) { 2460 res = rd.publicFields; 2461 if (res != null) return res; 2462 } 2463 2464 // No cached value available; compute value recursively. 2465 // Traverse in correct order for getField(). 2466 List<Field> fields = new ArrayList<>(); 2467 if (traversedInterfaces == null) { 2468 traversedInterfaces = new HashSet<>(); 2469 } 2470 2471 // Local fields 2472 Field[] tmp = privateGetDeclaredFields(true); 2473 addAll(fields, tmp); 2474 2475 // Direct superinterfaces, recursively 2476 for (Class<?> c : getInterfaces()) { 2477 if (!traversedInterfaces.contains(c)) { 2478 traversedInterfaces.add(c); 2479 addAll(fields, c.privateGetPublicFields(traversedInterfaces)); 2480 } 2481 } 2482 2483 // Direct superclass, recursively 2484 if (!isInterface()) { 2485 Class<?> c = getSuperclass(); 2486 if (c != null) { 2487 addAll(fields, c.privateGetPublicFields(traversedInterfaces)); 2488 } 2489 } 2490 2491 res = new Field[fields.size()]; 2492 fields.toArray(res); 2493 if (rd != null) { 2494 rd.publicFields = res; 2495 } 2496 return res; 2497 } 2498 2499 private static void addAll(Collection<Field> c, Field[] o) { 2500 for (int i = 0; i < o.length; i++) { 2501 c.add(o[i]); 2502 } 2503 } 2504 2505 2506 // 2507 // 2508 // java.lang.reflect.Constructor handling 2509 // 2510 // 2511 2512 // Returns an array of "root" constructors. These Constructor 2513 // objects must NOT be propagated to the outside world, but must 2514 // instead be copied via ReflectionFactory.copyConstructor. 2515 private Constructor<T>[] privateGetDeclaredConstructors(boolean publicOnly) { 2516 checkInitted(); 2517 Constructor<T>[] res; 2518 ReflectionData<T> rd = reflectionData(); 2519 if (rd != null) { 2520 res = publicOnly ? rd.publicConstructors : rd.declaredConstructors; 2521 if (res != null) return res; 2522 } 2523 // No cached value available; request value from VM 2524 if (isInterface()) { 2525 @SuppressWarnings("unchecked") 2526 Constructor<T>[] temporaryRes = (Constructor<T>[]) new Constructor<?>[0]; 2527 res = temporaryRes; 2528 } else { 2529 res = getDeclaredConstructors0(publicOnly); 2530 } 2531 if (rd != null) { 2532 if (publicOnly) { 2533 rd.publicConstructors = res; 2534 } else { 2535 rd.declaredConstructors = res; 2536 } 2537 } 2538 return res; 2539 } 2540 2541 // 2542 // 2543 // java.lang.reflect.Method handling 2544 // 2545 // 2546 2547 // Returns an array of "root" methods. These Method objects must NOT 2548 // be propagated to the outside world, but must instead be copied 2549 // via ReflectionFactory.copyMethod. 2550 private Method[] privateGetDeclaredMethods(boolean publicOnly) { 2551 checkInitted(); 2552 Method[] res; 2553 ReflectionData<T> rd = reflectionData(); 2554 if (rd != null) { 2555 res = publicOnly ? rd.declaredPublicMethods : rd.declaredMethods; 2556 if (res != null) return res; 2557 } 2558 // No cached value available; request value from VM 2559 res = Reflection.filterMethods(this, getDeclaredMethods0(publicOnly)); 2560 if (rd != null) { 2561 if (publicOnly) { 2562 rd.declaredPublicMethods = res; 2563 } else { 2564 rd.declaredMethods = res; 2565 } 2566 } 2567 return res; 2568 } 2569 2570 static class MethodArray { 2571 private Method[] methods; 2572 private int length; 2573 2574 MethodArray() { 2575 methods = new Method[20]; 2576 length = 0; 2577 } 2578 2579 void add(Method m) { 2580 if (length == methods.length) { 2581 methods = Arrays.copyOf(methods, 2 * methods.length); 2582 } 2583 methods[length++] = m; 2584 } 2585 2586 void addAll(Method[] ma) { 2587 for (int i = 0; i < ma.length; i++) { 2588 add(ma[i]); 2589 } 2590 } 2591 2592 void addAll(MethodArray ma) { 2593 for (int i = 0; i < ma.length(); i++) { 2594 add(ma.get(i)); 2595 } 2596 } 2597 2598 void addIfNotPresent(Method newMethod) { 2599 for (int i = 0; i < length; i++) { 2600 Method m = methods[i]; 2601 if (m == newMethod || (m != null && m.equals(newMethod))) { 2602 return; 2603 } 2604 } 2605 add(newMethod); 2606 } 2607 2608 void addAllIfNotPresent(MethodArray newMethods) { 2609 for (int i = 0; i < newMethods.length(); i++) { 2610 Method m = newMethods.get(i); 2611 if (m != null) { 2612 addIfNotPresent(m); 2613 } 2614 } 2615 } 2616 2617 int length() { 2618 return length; 2619 } 2620 2621 Method get(int i) { 2622 return methods[i]; 2623 } 2624 2625 void removeByNameAndSignature(Method toRemove) { 2626 for (int i = 0; i < length; i++) { 2627 Method m = methods[i]; 2628 if (m != null && 2629 m.getReturnType() == toRemove.getReturnType() && 2630 m.getName() == toRemove.getName() && 2631 arrayContentsEq(m.getParameterTypes(), 2632 toRemove.getParameterTypes())) { 2633 methods[i] = null; 2634 } 2635 } 2636 } 2637 2638 void compactAndTrim() { 2639 int newPos = 0; 2640 // Get rid of null slots 2641 for (int pos = 0; pos < length; pos++) { 2642 Method m = methods[pos]; 2643 if (m != null) { 2644 if (pos != newPos) { 2645 methods[newPos] = m; 2646 } 2647 newPos++; 2648 } 2649 } 2650 if (newPos != methods.length) { 2651 methods = Arrays.copyOf(methods, newPos); 2652 } 2653 } 2654 2655 Method[] getArray() { 2656 return methods; 2657 } 2658 } 2659 2660 2661 // Returns an array of "root" methods. These Method objects must NOT 2662 // be propagated to the outside world, but must instead be copied 2663 // via ReflectionFactory.copyMethod. 2664 private Method[] privateGetPublicMethods() { 2665 checkInitted(); 2666 Method[] res; 2667 ReflectionData<T> rd = reflectionData(); 2668 if (rd != null) { 2669 res = rd.publicMethods; 2670 if (res != null) return res; 2671 } 2672 2673 // No cached value available; compute value recursively. 2674 // Start by fetching public declared methods 2675 MethodArray methods = new MethodArray(); 2676 { 2677 Method[] tmp = privateGetDeclaredMethods(true); 2678 methods.addAll(tmp); 2679 } 2680 // Now recur over superclass and direct superinterfaces. 2681 // Go over superinterfaces first so we can more easily filter 2682 // out concrete implementations inherited from superclasses at 2683 // the end. 2684 MethodArray inheritedMethods = new MethodArray(); 2685 Class<?>[] interfaces = getInterfaces(); 2686 for (int i = 0; i < interfaces.length; i++) { 2687 inheritedMethods.addAll(interfaces[i].privateGetPublicMethods()); 2688 } 2689 if (!isInterface()) { 2690 Class<?> c = getSuperclass(); 2691 if (c != null) { 2692 MethodArray supers = new MethodArray(); 2693 supers.addAll(c.privateGetPublicMethods()); 2694 // Filter out concrete implementations of any 2695 // interface methods 2696 for (int i = 0; i < supers.length(); i++) { 2697 Method m = supers.get(i); 2698 if (m != null && !Modifier.isAbstract(m.getModifiers())) { 2699 inheritedMethods.removeByNameAndSignature(m); 2700 } 2701 } 2702 // Insert superclass's inherited methods before 2703 // superinterfaces' to satisfy getMethod's search 2704 // order 2705 supers.addAll(inheritedMethods); 2706 inheritedMethods = supers; 2707 } 2708 } 2709 // Filter out all local methods from inherited ones 2710 for (int i = 0; i < methods.length(); i++) { 2711 Method m = methods.get(i); 2712 inheritedMethods.removeByNameAndSignature(m); 2713 } 2714 methods.addAllIfNotPresent(inheritedMethods); 2715 methods.compactAndTrim(); 2716 res = methods.getArray(); 2717 if (rd != null) { 2718 rd.publicMethods = res; 2719 } 2720 return res; 2721 } 2722 2723 2724 // 2725 // Helpers for fetchers of one field, method, or constructor 2726 // 2727 2728 private static Field searchFields(Field[] fields, String name) { 2729 String internedName = name.intern(); 2730 for (int i = 0; i < fields.length; i++) { 2731 if (fields[i].getName() == internedName) { 2732 return getReflectionFactory().copyField(fields[i]); 2733 } 2734 } 2735 return null; 2736 } 2737 2738 private Field getField0(String name) throws NoSuchFieldException { 2739 // Note: the intent is that the search algorithm this routine 2740 // uses be equivalent to the ordering imposed by 2741 // privateGetPublicFields(). It fetches only the declared 2742 // public fields for each class, however, to reduce the number 2743 // of Field objects which have to be created for the common 2744 // case where the field being requested is declared in the 2745 // class which is being queried. 2746 Field res; 2747 // Search declared public fields 2748 if ((res = searchFields(privateGetDeclaredFields(true), name)) != null) { 2749 return res; 2750 } 2751 // Direct superinterfaces, recursively 2752 Class<?>[] interfaces = getInterfaces(); 2753 for (int i = 0; i < interfaces.length; i++) { 2754 Class<?> c = interfaces[i]; 2755 if ((res = c.getField0(name)) != null) { 2756 return res; 2757 } 2758 } 2759 // Direct superclass, recursively 2760 if (!isInterface()) { 2761 Class<?> c = getSuperclass(); 2762 if (c != null) { 2763 if ((res = c.getField0(name)) != null) { 2764 return res; 2765 } 2766 } 2767 } 2768 return null; 2769 } 2770 2771 private static Method searchMethods(Method[] methods, 2772 String name, 2773 Class<?>[] parameterTypes) 2774 { 2775 Method res = null; 2776 String internedName = name.intern(); 2777 for (int i = 0; i < methods.length; i++) { 2778 Method m = methods[i]; 2779 if (m.getName() == internedName 2780 && arrayContentsEq(parameterTypes, m.getParameterTypes()) 2781 && (res == null 2782 || res.getReturnType().isAssignableFrom(m.getReturnType()))) 2783 res = m; 2784 } 2785 2786 return (res == null ? res : getReflectionFactory().copyMethod(res)); 2787 } 2788 2789 2790 private Method getMethod0(String name, Class<?>[] parameterTypes) { 2791 // Note: the intent is that the search algorithm this routine 2792 // uses be equivalent to the ordering imposed by 2793 // privateGetPublicMethods(). It fetches only the declared 2794 // public methods for each class, however, to reduce the 2795 // number of Method objects which have to be created for the 2796 // common case where the method being requested is declared in 2797 // the class which is being queried. 2798 Method res; 2799 // Search declared public methods 2800 if ((res = searchMethods(privateGetDeclaredMethods(true), 2801 name, 2802 parameterTypes)) != null) { 2803 return res; 2804 } 2805 // Search superclass's methods 2806 if (!isInterface()) { 2807 Class<? super T> c = getSuperclass(); 2808 if (c != null) { 2809 if ((res = c.getMethod0(name, parameterTypes)) != null) { 2810 return res; 2811 } 2812 } 2813 } 2814 // Search superinterfaces' methods 2815 Class<?>[] interfaces = getInterfaces(); 2816 for (int i = 0; i < interfaces.length; i++) { 2817 Class<?> c = interfaces[i]; 2818 if ((res = c.getMethod0(name, parameterTypes)) != null) { 2819 return res; 2820 } 2821 } 2822 // Not found 2823 return null; 2824 } 2825 2826 private Constructor<T> getConstructor0(Class<?>[] parameterTypes, 2827 int which) throws NoSuchMethodException 2828 { 2829 Constructor<T>[] constructors = privateGetDeclaredConstructors((which == Member.PUBLIC)); 2830 for (Constructor<T> constructor : constructors) { 2831 if (arrayContentsEq(parameterTypes, 2832 constructor.getParameterTypes())) { 2833 return getReflectionFactory().copyConstructor(constructor); 2834 } 2835 } 2836 throw new NoSuchMethodException(getName() + ".<init>" + argumentTypesToString(parameterTypes)); 2837 } 2838 2839 // 2840 // Other helpers and base implementation 2841 // 2842 2843 private static boolean arrayContentsEq(Object[] a1, Object[] a2) { 2844 if (a1 == null) { 2845 return a2 == null || a2.length == 0; 2846 } 2847 2848 if (a2 == null) { 2849 return a1.length == 0; 2850 } 2851 2852 if (a1.length != a2.length) { 2853 return false; 2854 } 2855 2856 for (int i = 0; i < a1.length; i++) { 2857 if (a1[i] != a2[i]) { 2858 return false; 2859 } 2860 } 2861 2862 return true; 2863 } 2864 2865 private static Field[] copyFields(Field[] arg) { 2866 Field[] out = new Field[arg.length]; 2867 ReflectionFactory fact = getReflectionFactory(); 2868 for (int i = 0; i < arg.length; i++) { 2869 out[i] = fact.copyField(arg[i]); 2870 } 2871 return out; 2872 } 2873 2874 private static Method[] copyMethods(Method[] arg) { 2875 Method[] out = new Method[arg.length]; 2876 ReflectionFactory fact = getReflectionFactory(); 2877 for (int i = 0; i < arg.length; i++) { 2878 out[i] = fact.copyMethod(arg[i]); 2879 } 2880 return out; 2881 } 2882 2883 private static <U> Constructor<U>[] copyConstructors(Constructor<U>[] arg) { 2884 Constructor<U>[] out = arg.clone(); 2885 ReflectionFactory fact = getReflectionFactory(); 2886 for (int i = 0; i < out.length; i++) { 2887 out[i] = fact.copyConstructor(out[i]); 2888 } 2889 return out; 2890 } 2891 2892 private native Field[] getDeclaredFields0(boolean publicOnly); 2893 private native Method[] getDeclaredMethods0(boolean publicOnly); 2894 private native Constructor<T>[] getDeclaredConstructors0(boolean publicOnly); 2895 private native Class<?>[] getDeclaredClasses0(); 2896 2897 private static String argumentTypesToString(Class<?>[] argTypes) { 2898 StringBuilder buf = new StringBuilder(); 2899 buf.append("("); 2900 if (argTypes != null) { 2901 for (int i = 0; i < argTypes.length; i++) { 2902 if (i > 0) { 2903 buf.append(", "); 2904 } 2905 Class<?> c = argTypes[i]; 2906 buf.append((c == null) ? "null" : c.getName()); 2907 } 2908 } 2909 buf.append(")"); 2910 return buf.toString(); 2911 } 2912 2913 /** use serialVersionUID from JDK 1.1 for interoperability */ 2914 private static final long serialVersionUID = 3206093459760846163L; 2915 2916 2917 /** 2918 * Class Class is special cased within the Serialization Stream Protocol. 2919 * 2920 * A Class instance is written initially into an ObjectOutputStream in the 2921 * following format: 2922 * <pre> 2923 * {@code TC_CLASS} ClassDescriptor 2924 * A ClassDescriptor is a special cased serialization of 2925 * a {@code java.io.ObjectStreamClass} instance. 2926 * </pre> 2927 * A new handle is generated for the initial time the class descriptor 2928 * is written into the stream. Future references to the class descriptor 2929 * are written as references to the initial class descriptor instance. 2930 * 2931 * @see java.io.ObjectStreamClass 2932 */ 2933 private static final ObjectStreamField[] serialPersistentFields = 2934 new ObjectStreamField[0]; 2935 2936 2937 /** 2938 * Returns the assertion status that would be assigned to this 2939 * class if it were to be initialized at the time this method is invoked. 2940 * If this class has had its assertion status set, the most recent 2941 * setting will be returned; otherwise, if any package default assertion 2942 * status pertains to this class, the most recent setting for the most 2943 * specific pertinent package default assertion status is returned; 2944 * otherwise, if this class is not a system class (i.e., it has a 2945 * class loader) its class loader's default assertion status is returned; 2946 * otherwise, the system class default assertion status is returned. 2947 * <p> 2948 * Few programmers will have any need for this method; it is provided 2949 * for the benefit of the JRE itself. (It allows a class to determine at 2950 * the time that it is initialized whether assertions should be enabled.) 2951 * Note that this method is not guaranteed to return the actual 2952 * assertion status that was (or will be) associated with the specified 2953 * class when it was (or will be) initialized. 2954 * 2955 * @return the desired assertion status of the specified class. 2956 * @see java.lang.ClassLoader#setClassAssertionStatus 2957 * @see java.lang.ClassLoader#setPackageAssertionStatus 2958 * @see java.lang.ClassLoader#setDefaultAssertionStatus 2959 * @since 1.4 2960 */ 2961 public boolean desiredAssertionStatus() { 2962 ClassLoader loader = getClassLoader(); 2963 // If the loader is null this is a system class, so ask the VM 2964 if (loader == null) 2965 return desiredAssertionStatus0(this); 2966 2967 // If the classloader has been initialized with the assertion 2968 // directives, ask it. Otherwise, ask the VM. 2969 synchronized(loader.assertionLock) { 2970 if (loader.classAssertionStatus != null) { 2971 return loader.desiredAssertionStatus(getName()); 2972 } 2973 } 2974 return desiredAssertionStatus0(this); 2975 } 2976 2977 // Retrieves the desired assertion status of this class from the VM 2978 private static native boolean desiredAssertionStatus0(Class<?> clazz); 2979 2980 /** 2981 * Returns true if and only if this class was declared as an enum in the 2982 * source code. 2983 * 2984 * @return true if and only if this class was declared as an enum in the 2985 * source code 2986 * @since 1.5 2987 */ 2988 public boolean isEnum() { 2989 // An enum must both directly extend java.lang.Enum and have 2990 // the ENUM bit set; classes for specialized enum constants 2991 // don't do the former. 2992 return (this.getModifiers() & ENUM) != 0 && 2993 this.getSuperclass() == java.lang.Enum.class; 2994 } 2995 2996 // Fetches the factory for reflective objects 2997 private static ReflectionFactory getReflectionFactory() { 2998 if (reflectionFactory == null) { 2999 reflectionFactory = 3000 java.security.AccessController.doPrivileged 3001 (new sun.reflect.ReflectionFactory.GetReflectionFactoryAction()); 3002 } 3003 return reflectionFactory; 3004 } 3005 private static ReflectionFactory reflectionFactory; 3006 3007 // To be able to query system properties as soon as they're available 3008 private static boolean initted = false; 3009 private static void checkInitted() { 3010 if (initted) return; 3011 AccessController.doPrivileged(new PrivilegedAction<Void>() { 3012 public Void run() { 3013 // Tests to ensure the system properties table is fully 3014 // initialized. This is needed because reflection code is 3015 // called very early in the initialization process (before 3016 // command-line arguments have been parsed and therefore 3017 // these user-settable properties installed.) We assume that 3018 // if System.out is non-null then the System class has been 3019 // fully initialized and that the bulk of the startup code 3020 // has been run. 3021 3022 if (System.out == null) { 3023 // java.lang.System not yet fully initialized 3024 return null; 3025 } 3026 3027 // Doesn't use Boolean.getBoolean to avoid class init. 3028 String val = 3029 System.getProperty("sun.reflect.noCaches"); 3030 if (val != null && val.equals("true")) { 3031 useCaches = false; 3032 } 3033 3034 initted = true; 3035 return null; 3036 } 3037 }); 3038 } 3039 3040 /** 3041 * Returns the elements of this enum class or null if this 3042 * Class object does not represent an enum type. 3043 * 3044 * @return an array containing the values comprising the enum class 3045 * represented by this Class object in the order they're 3046 * declared, or null if this Class object does not 3047 * represent an enum type 3048 * @since 1.5 3049 */ 3050 public T[] getEnumConstants() { 3051 T[] values = getEnumConstantsShared(); 3052 return (values != null) ? values.clone() : null; 3053 } 3054 3055 /** 3056 * Returns the elements of this enum class or null if this 3057 * Class object does not represent an enum type; 3058 * identical to getEnumConstants except that the result is 3059 * uncloned, cached, and shared by all callers. 3060 */ 3061 T[] getEnumConstantsShared() { 3062 if (enumConstants == null) { 3063 if (!isEnum()) return null; 3064 try { 3065 final Method values = getMethod("values"); 3066 java.security.AccessController.doPrivileged( 3067 new java.security.PrivilegedAction<Void>() { 3068 public Void run() { 3069 values.setAccessible(true); 3070 return null; 3071 } 3072 }); 3073 @SuppressWarnings("unchecked") 3074 T[] temporaryConstants = (T[])values.invoke(null); 3075 enumConstants = temporaryConstants; 3076 } 3077 // These can happen when users concoct enum-like classes 3078 // that don't comply with the enum spec. 3079 catch (InvocationTargetException | NoSuchMethodException | 3080 IllegalAccessException ex) { return null; } 3081 } 3082 return enumConstants; 3083 } 3084 private volatile transient T[] enumConstants = null; 3085 3086 /** 3087 * Returns a map from simple name to enum constant. This package-private 3088 * method is used internally by Enum to implement 3089 * {@code public static <T extends Enum<T>> T valueOf(Class<T>, String)} 3090 * efficiently. Note that the map is returned by this method is 3091 * created lazily on first use. Typically it won't ever get created. 3092 */ 3093 Map<String, T> enumConstantDirectory() { 3094 if (enumConstantDirectory == null) { 3095 T[] universe = getEnumConstantsShared(); 3096 if (universe == null) 3097 throw new IllegalArgumentException( 3098 getName() + " is not an enum type"); 3099 Map<String, T> m = new HashMap<>(2 * universe.length); 3100 for (T constant : universe) 3101 m.put(((Enum<?>)constant).name(), constant); 3102 enumConstantDirectory = m; 3103 } 3104 return enumConstantDirectory; 3105 } 3106 private volatile transient Map<String, T> enumConstantDirectory = null; 3107 3108 /** 3109 * Casts an object to the class or interface represented 3110 * by this {@code Class} object. 3111 * 3112 * @param obj the object to be cast 3113 * @return the object after casting, or null if obj is null 3114 * 3115 * @throws ClassCastException if the object is not 3116 * null and is not assignable to the type T. 3117 * 3118 * @since 1.5 3119 */ 3120 @SuppressWarnings("unchecked") 3121 public T cast(Object obj) { 3122 if (obj != null && !isInstance(obj)) 3123 throw new ClassCastException(cannotCastMsg(obj)); 3124 return (T) obj; 3125 } 3126 3127 private String cannotCastMsg(Object obj) { 3128 return "Cannot cast " + obj.getClass().getName() + " to " + getName(); 3129 } 3130 3131 /** 3132 * Casts this {@code Class} object to represent a subclass of the class 3133 * represented by the specified class object. Checks that the cast 3134 * is valid, and throws a {@code ClassCastException} if it is not. If 3135 * this method succeeds, it always returns a reference to this class object. 3136 * 3137 * <p>This method is useful when a client needs to "narrow" the type of 3138 * a {@code Class} object to pass it to an API that restricts the 3139 * {@code Class} objects that it is willing to accept. A cast would 3140 * generate a compile-time warning, as the correctness of the cast 3141 * could not be checked at runtime (because generic types are implemented 3142 * by erasure). 3143 * 3144 * @return this {@code Class} object, cast to represent a subclass of 3145 * the specified class object. 3146 * @throws ClassCastException if this {@code Class} object does not 3147 * represent a subclass of the specified class (here "subclass" includes 3148 * the class itself). 3149 * @since 1.5 3150 */ 3151 @SuppressWarnings("unchecked") 3152 public <U> Class<? extends U> asSubclass(Class<U> clazz) { 3153 if (clazz.isAssignableFrom(this)) 3154 return (Class<? extends U>) this; 3155 else 3156 throw new ClassCastException(this.toString()); 3157 } 3158 3159 /** 3160 * @throws NullPointerException {@inheritDoc} 3161 * @since 1.5 3162 */ 3163 @SuppressWarnings("unchecked") 3164 public <A extends Annotation> A getAnnotation(Class<A> annotationClass) { 3165 Objects.requireNonNull(annotationClass); 3166 3167 initAnnotationsIfNecessary(); 3168 return (A) annotations.get(annotationClass); 3169 } 3170 3171 /** 3172 * {@inheritDoc} 3173 * @throws NullPointerException {@inheritDoc} 3174 * @since 1.5 3175 */ 3176 @Override 3177 public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) { 3178 return GenericDeclaration.super.isAnnotationPresent(annotationClass); 3179 } 3180 3181 /** 3182 * @throws NullPointerException {@inheritDoc} 3183 * @since 1.8 3184 */ 3185 @Override 3186 public <A extends Annotation> A[] getAnnotationsByType(Class<A> annotationClass) { 3187 Objects.requireNonNull(annotationClass); 3188 3189 initAnnotationsIfNecessary(); 3190 return AnnotationSupport.getMultipleAnnotations(annotations, annotationClass); 3191 } 3192 3193 /** 3194 * @since 1.5 3195 */ 3196 public Annotation[] getAnnotations() { 3197 initAnnotationsIfNecessary(); 3198 return AnnotationParser.toArray(annotations); 3199 } 3200 3201 /** 3202 * @throws NullPointerException {@inheritDoc} 3203 * @since 1.8 3204 */ 3205 @Override 3206 @SuppressWarnings("unchecked") 3207 public <A extends Annotation> A getDeclaredAnnotation(Class<A> annotationClass) { 3208 Objects.requireNonNull(annotationClass); 3209 3210 initAnnotationsIfNecessary(); 3211 return (A) declaredAnnotations.get(annotationClass); 3212 } 3213 3214 /** 3215 * @throws NullPointerException {@inheritDoc} 3216 * @since 1.8 3217 */ 3218 @Override 3219 public <A extends Annotation> A[] getDeclaredAnnotationsByType(Class<A> annotationClass) { 3220 Objects.requireNonNull(annotationClass); 3221 3222 initAnnotationsIfNecessary(); 3223 return AnnotationSupport.getMultipleAnnotations(declaredAnnotations, annotationClass); 3224 } 3225 3226 /** 3227 * @since 1.5 3228 */ 3229 public Annotation[] getDeclaredAnnotations() { 3230 initAnnotationsIfNecessary(); 3231 return AnnotationParser.toArray(declaredAnnotations); 3232 } 3233 3234 // Annotations cache 3235 private transient Map<Class<? extends Annotation>, Annotation> annotations; 3236 private transient Map<Class<? extends Annotation>, Annotation> declaredAnnotations; 3237 // Value of classRedefinedCount when we last cleared the cached annotations and declaredAnnotations fields 3238 private transient int lastAnnotationsRedefinedCount = 0; 3239 3240 // Clears cached values that might possibly have been obsoleted by 3241 // a class redefinition. 3242 private void clearAnnotationCachesOnClassRedefinition() { 3243 if (lastAnnotationsRedefinedCount != classRedefinedCount) { 3244 annotations = declaredAnnotations = null; 3245 lastAnnotationsRedefinedCount = classRedefinedCount; 3246 } 3247 } 3248 3249 private synchronized void initAnnotationsIfNecessary() { 3250 clearAnnotationCachesOnClassRedefinition(); 3251 if (annotations != null) 3252 return; 3253 declaredAnnotations = AnnotationParser.parseAnnotations( 3254 getRawAnnotations(), getConstantPool(), this); 3255 Class<?> superClass = getSuperclass(); 3256 if (superClass == null) { 3257 annotations = declaredAnnotations; 3258 } else { 3259 annotations = new HashMap<>(); 3260 superClass.initAnnotationsIfNecessary(); 3261 for (Map.Entry<Class<? extends Annotation>, Annotation> e : superClass.annotations.entrySet()) { 3262 Class<? extends Annotation> annotationClass = e.getKey(); 3263 if (AnnotationType.getInstance(annotationClass).isInherited()) 3264 annotations.put(annotationClass, e.getValue()); 3265 } 3266 annotations.putAll(declaredAnnotations); 3267 } 3268 } 3269 3270 // Annotation types cache their internal (AnnotationType) form 3271 3272 private AnnotationType annotationType; 3273 3274 void setAnnotationType(AnnotationType type) { 3275 annotationType = type; 3276 } 3277 3278 AnnotationType getAnnotationType() { 3279 return annotationType; 3280 } 3281 3282 /* Backing store of user-defined values pertaining to this class. 3283 * Maintained by the ClassValue class. 3284 */ 3285 transient ClassValue.ClassValueMap classValueMap; 3286 3287 /** 3288 * Returns an AnnotatedType object that represents the use of a type to specify 3289 * the superclass of the entity represented by this Class. (The <em>use</em> of type 3290 * Foo to specify the superclass in '... extends Foo' is distinct from the 3291 * <em>declaration</em> of type Foo.) 3292 * 3293 * If this Class represents a class type whose declaration does not explicitly 3294 * indicate an annotated superclass, the return value is null. 3295 * 3296 * If this Class represents either the Object class, an interface type, an 3297 * array type, a primitive type, or void, the return value is null. 3298 * 3299 * @since 1.8 3300 */ 3301 public AnnotatedType getAnnotatedSuperclass() { 3302 return TypeAnnotationParser.buildAnnotatedSuperclass(getRawTypeAnnotations(), getConstantPool(), this); 3303 } 3304 3305 /** 3306 * Returns an array of AnnotatedType objects that represent the use of types to 3307 * specify superinterfaces of the entity represented by this Class. (The <em>use</em> 3308 * of type Foo to specify a superinterface in '... implements Foo' is 3309 * distinct from the <em>declaration</em> of type Foo.) 3310 * 3311 * If this Class represents a class, the return value is an array 3312 * containing objects representing the uses of interface types to specify 3313 * interfaces implemented by the class. The order of the objects in the 3314 * array corresponds to the order of the interface types used in the 3315 * 'implements' clause of the declaration of this Class. 3316 * 3317 * If this Class represents an interface, the return value is an array 3318 * containing objects representing the uses of interface types to specify 3319 * interfaces directly extended by the interface. The order of the objects in 3320 * the array corresponds to the order of the interface types used in the 3321 * 'extends' clause of the declaration of this Class. 3322 * 3323 * If this Class represents a class or interface whose declaration does not 3324 * explicitly indicate any annotated superinterfaces, the return value is an 3325 * array of length 0. 3326 * 3327 * If this Class represents either the Object class, an array type, a 3328 * primitive type, or void, the return value is an array of length 0. 3329 * 3330 * @since 1.8 3331 */ 3332 public AnnotatedType[] getAnnotatedInterfaces() { 3333 return TypeAnnotationParser.buildAnnotatedInterfaces(getRawTypeAnnotations(), getConstantPool(), this); 3334 } 3335 }