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