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