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