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