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