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