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