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