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