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