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