1 /* 2 * Copyright (C) 2014 The Android Open Source Project 3 * Copyright (c) 1994, 2021, Oracle and/or its affiliates. All rights reserved. 4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 5 * 6 * This code is free software; you can redistribute it and/or modify it 7 * under the terms of the GNU General Public License version 2 only, as 8 * published by the Free Software Foundation. Oracle designates this 9 * particular file as subject to the "Classpath" exception as provided 10 * by Oracle in the LICENSE file that accompanied this code. 11 * 12 * This code is distributed in the hope that it will be useful, but WITHOUT 13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 14 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 15 * version 2 for more details (a copy is included in the LICENSE file that 16 * accompanied this code). 17 * 18 * You should have received a copy of the GNU General Public License version 19 * 2 along with this work; if not, write to the Free Software Foundation, 20 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 21 * 22 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 23 * or visit www.oracle.com if you need additional information or have any 24 * questions. 25 */ 26 27 package java.lang; 28 29 import dalvik.annotation.compat.VersionCodes; 30 import dalvik.annotation.optimization.FastNative; 31 import dalvik.system.ClassExt; 32 import dalvik.system.VMRuntime; 33 34 import java.io.Serializable; 35 import java.lang.annotation.Annotation; 36 import java.lang.annotation.Inherited; 37 import java.lang.constant.ClassDesc; 38 import java.lang.constant.ClassDesc; 39 import java.lang.constant.Constable; 40 import java.lang.invoke.TypeDescriptor; 41 import java.lang.invoke.MethodHandles; 42 import java.lang.ref.SoftReference; 43 import java.io.IOException; 44 import java.io.InputStream; 45 import java.io.ObjectStreamField; 46 import java.lang.invoke.TypeDescriptor; 47 import java.lang.invoke.MethodHandles; 48 import java.lang.reflect.AnnotatedElement; 49 import java.lang.reflect.Array; 50 import java.lang.reflect.Constructor; 51 import java.lang.reflect.Executable; 52 import java.lang.reflect.Field; 53 import java.lang.reflect.GenericArrayType; 54 import java.lang.reflect.GenericDeclaration; 55 import java.lang.reflect.InvocationTargetException; 56 import java.lang.reflect.Member; 57 import java.lang.reflect.Method; 58 import java.lang.reflect.Modifier; 59 import java.lang.reflect.Parameter; 60 import java.lang.reflect.Proxy; 61 import java.lang.reflect.RecordComponent; 62 import java.lang.reflect.Type; 63 import java.lang.reflect.TypeVariable; 64 import java.lang.constant.Constable; 65 import java.net.URL; 66 import java.security.AccessController; 67 import java.security.PrivilegedAction; 68 import java.util.ArrayList; 69 import java.util.Arrays; 70 import java.util.Collection; 71 import java.util.Collections; 72 import java.util.HashMap; 73 import java.util.HashSet; 74 import java.util.LinkedHashMap; 75 import java.util.LinkedHashSet; 76 import java.util.List; 77 import java.util.Map; 78 import java.util.Objects; 79 import java.util.Optional; 80 import java.util.Set; 81 import java.util.StringJoiner; 82 import java.util.stream.Collectors; 83 import jdk.internal.HotSpotIntrinsicCandidate; 84 import jdk.internal.vm.annotation.IntrinsicCandidate; 85 import jdk.internal.misc.Unsafe; 86 import jdk.internal.misc.VM; 87 import libcore.reflect.GenericSignatureParser; 88 import libcore.reflect.InternalNames; 89 import libcore.reflect.RecordComponents; 90 import libcore.reflect.Types; 91 import libcore.util.BasicLruCache; 92 import libcore.util.CollectionUtils; 93 import libcore.util.EmptyArray; 94 95 import jdk.internal.misc.Unsafe; 96 import jdk.internal.reflect.CallerSensitive; 97 import jdk.internal.reflect.Reflection; 98 import jdk.internal.vm.annotation.IntrinsicCandidate; 99 import sun.invoke.util.Wrapper; 100 import sun.security.util.SecurityConstants; 101 import sun.reflect.misc.ReflectUtil; 102 103 104 // Android-changed: Removed javadoc related to hidden classes. 105 // Android-changed: Removed javadoc related to loading from class file. 106 /** 107 * Instances of the class {@code Class} represent classes and 108 * interfaces in a running Java application. An enum class and a record 109 * class are kinds of class; an annotation interface is a kind of 110 * interface. Every array also belongs to a class that is reflected as 111 * a {@code Class} object that is shared by all arrays with the same 112 * element type and number of dimensions. The primitive Java types 113 * ({@code boolean}, {@code byte}, {@code char}, {@code short}, {@code 114 * int}, {@code long}, {@code float}, and {@code double}), and the 115 * keyword {@code void} are also represented as {@code Class} objects. 116 * 117 * <p> {@code Class} has no public constructor. Instead a {@code Class} 118 * object is constructed automatically by the Java Virtual Machine when 119 * a class is derived from the bytes of a {@code class} file through 120 * the invocation of one of the following methods: 121 * <ul> 122 * <li> {@link ClassLoader#defineClass(String, byte[], int, int) ClassLoader::defineClass} 123 * </ul> 124 * 125 * <p> The methods of class {@code Class} expose many characteristics of a 126 * class or interface. Most characteristics are derived from the {@code class} 127 * file that the class loader passed to the Java Virtual Machine. A few 128 * characteristics are determined by the class loading environment at run time. 129 * 130 * <p> The following example uses a {@code Class} object to print the 131 * class name of an object: 132 * 133 * <blockquote><pre> 134 * void printClassName(Object obj) { 135 * System.out.println("The class of " + obj + 136 * " is " + obj.getClass().getName()); 137 * } 138 * </pre></blockquote> 139 * 140 * It is also possible to get the {@code Class} object for a named 141 * class or interface (or for {@code void}) using a <i>class literal</i>. 142 * For example: 143 * 144 * <blockquote> 145 * {@code System.out.println("The name of class Foo is: "+Foo.class.getName());} 146 * </blockquote> 147 * 148 * <p> Some methods of class {@code Class} expose whether the declaration of 149 * a class or interface in Java source code was <em>enclosed</em> within 150 * another declaration. Other methods describe how a class or interface 151 * is situated in a <em>nest</em>. A <a id="nest">nest</a> is a set of 152 * classes and interfaces, in the same run-time package, that 153 * allow mutual access to their {@code private} members. 154 * The classes and interfaces are known as <em>nestmates</em>. 155 * One nestmate acts as the 156 * <em>nest host</em>, and enumerates the other nestmates which 157 * belong to the nest; each of them in turn records it as the nest host. 158 * The classes and interfaces which belong to a nest, including its host, are 159 * determined when 160 * {@code class} files are generated, for example, a Java compiler 161 * will typically record a top-level class as the host of a nest where the 162 * other members are the classes and interfaces whose declarations are 163 * enclosed within the top-level class declaration. 164 * 165 * <p> Some methods of class {@code Class} expose whether the declaration of 166 * a class or interface in Java source code was <em>enclosed</em> within 167 * another declaration. Other methods describe how a class or interface 168 * is situated in a <em>nest</em>. A <a id="nest">nest</a> is a set of 169 * classes and interfaces, in the same run-time package, that 170 * allow mutual access to their {@code private} members. 171 * The classes and interfaces are known as <em>nestmates</em>. 172 * One nestmate acts as the 173 * <em>nest host</em>, and enumerates the other nestmates which 174 * belong to the nest; each of them in turn records it as the nest host. 175 * The classes and interfaces which belong to a nest, including its host, are 176 * determined when 177 * {@code class} files are generated, for example, a Java compiler 178 * will typically record a top-level class as the host of a nest where the 179 * other members are the classes and interfaces whose declarations are 180 * enclosed within the top-level class declaration. 181 * 182 * @param <T> the type of the class modeled by this {@code Class} 183 * object. For example, the type of {@code String.class} is {@code 184 * Class<String>}. Use {@code Class<?>} if the class being modeled is 185 * unknown. 186 * 187 * @see java.lang.ClassLoader#defineClass(byte[], int, int) 188 * @since 1.0 189 * @jls 15.8.2 Class Literals 190 */ 191 public final class Class<T> implements java.io.Serializable, 192 GenericDeclaration, 193 Type, 194 AnnotatedElement, 195 TypeDescriptor.OfField<Class<?>>, 196 Constable { 197 private static final int ANNOTATION= 0x00002000; 198 private static final int ENUM = 0x00004000; 199 private static final int SYNTHETIC = 0x00001000; 200 private static final int FINALIZABLE = 0x80000000; 201 202 /** defining class loader, or null for the "bootstrap" system loader. */ 203 private transient ClassLoader classLoader; 204 205 /** 206 * For array classes, the component class object for instanceof/checkcast (for String[][][], 207 * this will be String[][]). null for non-array classes. 208 */ 209 private transient Class<?> componentType; 210 211 /** 212 * DexCache of resolved constant pool entries. Will be null for certain runtime-generated classes 213 * e.g. arrays and primitive classes. 214 */ 215 private transient Object dexCache; 216 217 /** 218 * Extra data that only some classes possess. This is allocated lazily as needed. 219 */ 220 private transient ClassExt extData; 221 222 /** 223 * The interface table (iftable_) contains pairs of a interface class and an array of the 224 * interface methods. There is one pair per interface supported by this class. That 225 * means one pair for each interface we support directly, indirectly via superclass, or 226 * indirectly via a superinterface. This will be null if neither we nor our superclass 227 * implement any interfaces. 228 * 229 * Why we need this: given "class Foo implements Face", declare "Face faceObj = new Foo()". 230 * Invoke faceObj.blah(), where "blah" is part of the Face interface. We can't easily use a 231 * single vtable. 232 * 233 * For every interface a concrete class implements, we create an array of the concrete vtable_ 234 * methods for the methods in the interface. 235 */ 236 private transient Object[] ifTable; 237 238 /** Lazily computed name of this class; always prefer calling getName(). */ 239 private transient String name; 240 241 /** The superclass, or null if this is java.lang.Object, an interface or primitive type. */ 242 private transient Class<? super T> superClass; 243 244 /** 245 * Virtual method table (vtable), for use by "invoke-virtual". The vtable from the superclass 246 * is copied in, and virtual methods from our class either replace those from the super or are 247 * appended. For abstract classes, methods may be created in the vtable that aren't in 248 * virtual_ methods_ for miranda methods. 249 */ 250 private transient Object vtable; 251 252 /** Declared fields. */ 253 private transient long fields; 254 255 /** All methods with this class as the base for virtual dispatch. */ 256 private transient long methods; 257 258 /** access flags; low 16 bits are defined by VM spec */ 259 private transient int accessFlags; 260 261 /** Class flags to help the GC with object scanning. */ 262 private transient int classFlags; 263 264 /** 265 * Total size of the Class instance; used when allocating storage on GC heap. 266 * See also {@link Class#objectSize}. 267 */ 268 private transient int classSize; 269 270 /** 271 * tid used to check for recursive static initializer invocation. 272 */ 273 private transient int clinitThreadId; 274 275 /** 276 * Class def index from dex file. An index of 65535 indicates that there is no class definition, 277 * for example for an array type. 278 * TODO: really 16bits as type indices are 16bit. 279 */ 280 private transient int dexClassDefIndex; 281 282 /** 283 * Class type index from dex file, lazily computed. An index of 65535 indicates that the type 284 * index isn't known. Volatile to avoid double-checked locking bugs. 285 * TODO: really 16bits as type indices are 16bit. 286 */ 287 private transient volatile int dexTypeIndex; 288 289 /** Number of instance fields that are object references. */ 290 private transient int numReferenceInstanceFields; 291 292 /** Number of static fields that are object references. */ 293 private transient int numReferenceStaticFields; 294 295 /** 296 * Total object size; used when allocating storage on GC heap. For interfaces and abstract 297 * classes this will be zero. See also {@link Class#classSize}. 298 */ 299 private transient int objectSize; 300 301 /** 302 * Aligned object size for allocation fast path. The value is max int if the object is 303 * uninitialized or finalizable, otherwise the aligned object size. 304 */ 305 private transient int objectSizeAllocFastPath; 306 307 /** 308 * The lower 16 bits is the primitive type value, or 0 if not a primitive type; set for 309 * generated primitive classes. 310 */ 311 private transient int primitiveType; 312 313 /** Bitmap of offsets of iFields. */ 314 private transient int referenceInstanceOffsets; 315 316 /** State of class initialization */ 317 private transient int status; 318 319 /** Offset of the first virtual method copied from an interface in the methods array. */ 320 private transient short copiedMethodsOffset; 321 322 /** Offset of the first virtual method defined in this class in the methods array. */ 323 private transient short virtualMethodsOffset; 324 325 /* 326 * Private constructor. Only the Java Virtual Machine creates Class objects. 327 * This constructor is not used and prevents the default constructor being 328 * generated. 329 */ Class()330 private Class() {} 331 Class(ClassLoader loader, Class<?> arrayComponentType)332 private Class(ClassLoader loader, Class<?> arrayComponentType) { 333 // Initialize final field for classLoader. The initialization value of non-null 334 // prevents future JIT optimizations from assuming this final field is null. 335 classLoader = loader; 336 componentType = arrayComponentType; 337 } 338 339 /** 340 * Converts the object to a string. The string representation is the 341 * string "class" or "interface", followed by a space, and then by the 342 * name of the class in the format returned by {@code getName}. 343 * If this {@code Class} object represents a primitive type, 344 * this method returns the name of the primitive type. If 345 * this {@code Class} object represents void this method returns 346 * "void". If this {@code Class} object represents an array type, 347 * this method returns "class " followed by {@code getName}. 348 * 349 * @return a string representation of this {@code Class} object. 350 */ toString()351 public String toString() { 352 return (isInterface() ? "interface " : (isPrimitive() ? "" : "class ")) 353 + getName(); 354 } 355 356 /** 357 * Returns a string describing this {@code Class}, including 358 * information about modifiers and type parameters. 359 * 360 * The string is formatted as a list of type modifiers, if any, 361 * followed by the kind of type (empty string for primitive types 362 * and {@code class}, {@code enum}, {@code interface}, 363 * {@code @interface}, or {@code record} as appropriate), followed 364 * by the type's name, followed by an angle-bracketed 365 * comma-separated list of the type's type parameters, if any, 366 * including informative bounds on the type parameters, if any. 367 * 368 * A space is used to separate modifiers from one another and to 369 * separate any modifiers from the kind of type. The modifiers 370 * occur in canonical order. If there are no type parameters, the 371 * type parameter list is elided. 372 * 373 * For an array type, the string starts with the type name, 374 * followed by an angle-bracketed comma-separated list of the 375 * type's type parameters, if any, followed by a sequence of 376 * {@code []} characters, one set of brackets per dimension of 377 * the array. 378 * 379 * <p>Note that since information about the runtime representation 380 * of a type is being generated, modifiers not present on the 381 * originating source code or illegal on the originating source 382 * code may be present. 383 * 384 * @return a string describing this {@code Class}, including 385 * information about modifiers and type parameters 386 * 387 * @since 1.8 388 */ toGenericString()389 public String toGenericString() { 390 if (isPrimitive()) { 391 return toString(); 392 } else { 393 StringBuilder sb = new StringBuilder(); 394 Class<?> component = this; 395 int arrayDepth = 0; 396 397 if (isArray()) { 398 do { 399 arrayDepth++; 400 component = component.getComponentType(); 401 } while (component.isArray()); 402 sb.append(component.getName()); 403 } else { 404 // Class modifiers are a superset of interface modifiers 405 int modifiers = getModifiers() & Modifier.classModifiers(); 406 if (modifiers != 0) { 407 sb.append(Modifier.toString(modifiers)); 408 sb.append(' '); 409 } 410 411 if (isAnnotation()) { 412 sb.append('@'); 413 } 414 if (isInterface()) { // Note: all annotation interfaces are interfaces 415 sb.append("interface"); 416 } else { 417 if (isEnum()) 418 sb.append("enum"); 419 else if (isRecord()) 420 sb.append("record"); 421 else 422 sb.append("class"); 423 } 424 sb.append(' '); 425 sb.append(getName()); 426 } 427 428 TypeVariable<?>[] typeparms = component.getTypeParameters(); 429 if (typeparms.length > 0) { 430 // Android-changed: Don't print the generic string of inner types on Android 14 or 431 // lower due to app compatibility. 432 if (VMRuntime.getSdkVersion() >= VersionCodes.VANILLA_ICE_CREAM) { 433 sb.append(Arrays.stream(typeparms) 434 .map(Class::typeVarBounds) 435 .collect(Collectors.joining(",", "<", ">"))); 436 } else { 437 StringJoiner sj = new StringJoiner(",", "<", ">"); 438 for(TypeVariable<?> typeparm: typeparms) { 439 sj.add(typeparm.getTypeName()); 440 } 441 sb.append(sj.toString()); 442 } 443 } 444 445 if (arrayDepth > 0) sb.append("[]".repeat(arrayDepth)); 446 447 return sb.toString(); 448 } 449 } 450 typeVarBounds(TypeVariable<?> typeVar)451 static String typeVarBounds(TypeVariable<?> typeVar) { 452 Type[] bounds = typeVar.getBounds(); 453 if (bounds.length == 1 && bounds[0].equals(Object.class)) { 454 return typeVar.getName(); 455 } else { 456 return typeVar.getName() + " extends " + 457 Arrays.stream(bounds) 458 .map(Type::getTypeName) 459 .collect(Collectors.joining(" & ")); 460 } 461 } 462 463 /** 464 * Returns the {@code Class} object associated with the class or 465 * interface with the given string name. Invoking this method is 466 * equivalent to: 467 * 468 * <blockquote> 469 * {@code Class.forName(className, true, currentLoader)} 470 * </blockquote> 471 * 472 * where {@code currentLoader} denotes the defining class loader of 473 * the current class. 474 * 475 * <p> For example, the following code fragment returns the 476 * runtime {@code Class} descriptor for the class named 477 * {@code java.lang.Thread}: 478 * 479 * <blockquote> 480 * {@code Class t = Class.forName("java.lang.Thread")} 481 * </blockquote> 482 * <p> 483 * A call to {@code forName("X")} causes the class named 484 * {@code X} to be initialized. 485 * 486 * @param className the fully qualified name of the desired class. 487 * @return the {@code Class} object for the class with the 488 * specified name. 489 * @throws LinkageError if the linkage fails 490 * @throws ExceptionInInitializerError if the initialization provoked 491 * by this method fails 492 * @throws ClassNotFoundException if the class cannot be located 493 * 494 * @jls 12.2 Loading of Classes and Interfaces 495 * @jls 12.3 Linking of Classes and Interfaces 496 * @jls 12.4 Initialization of Classes and Interfaces 497 */ 498 @CallerSensitive forName(String className)499 public static Class<?> forName(String className) 500 throws ClassNotFoundException { 501 Class<?> caller = Reflection.getCallerClass(); 502 return forName(className, true, ClassLoader.getClassLoader(caller)); 503 } 504 505 // Android-changed: Remove SecurityException javadoc. 506 /** 507 * Returns the {@code Class} object associated with the class or 508 * interface with the given string name, using the given class loader. 509 * Given the fully qualified name for a class or interface (in the same 510 * format returned by {@code getName}) this method attempts to 511 * locate and load the class or interface. The specified class 512 * loader is used to load the class or interface. If the parameter 513 * {@code loader} is null, the class is loaded through the bootstrap 514 * class loader. The class is initialized only if the 515 * {@code initialize} parameter is {@code true} and if it has 516 * not been initialized earlier. 517 * 518 * <p> If {@code name} denotes a primitive type or void, an attempt 519 * will be made to locate a user-defined class in the unnamed package whose 520 * name is {@code name}. Therefore, this method cannot be used to 521 * obtain any of the {@code Class} objects representing primitive 522 * types or void. 523 * 524 * <p> If {@code name} denotes an array class, the component type of 525 * the array class is loaded but not initialized. 526 * 527 * <p> For example, in an instance method the expression: 528 * 529 * <blockquote> 530 * {@code Class.forName("Foo")} 531 * </blockquote> 532 * 533 * is equivalent to: 534 * 535 * <blockquote> 536 * {@code Class.forName("Foo", true, this.getClass().getClassLoader())} 537 * </blockquote> 538 * 539 * Note that this method throws errors related to loading, linking 540 * or initializing as specified in Sections {@jls 12.2}, {@jls 541 * 12.3}, and {@jls 12.4} of <cite>The Java Language 542 * Specification</cite>. 543 * Note that this method does not check whether the requested class 544 * is accessible to its caller. 545 * 546 * @param name fully qualified name of the desired class 547 548 * @param initialize if {@code true} the class will be initialized 549 * (which implies linking). See Section {@jls 550 * 12.4} of <cite>The Java Language 551 * Specification</cite>. 552 * @param loader class loader from which the class must be loaded 553 * @return class object representing the desired class 554 * 555 * @throws LinkageError if the linkage fails 556 * @throws ExceptionInInitializerError if the initialization provoked 557 * by this method fails 558 * @throws ClassNotFoundException if the class cannot be located by 559 * the specified class loader 560 * 561 * @see java.lang.Class#forName(String) 562 * @see java.lang.ClassLoader 563 * 564 * @jls 12.2 Loading of Classes and Interfaces 565 * @jls 12.3 Linking of Classes and Interfaces 566 * @jls 12.4 Initialization of Classes and Interfaces 567 * @since 1.2 568 */ 569 @CallerSensitive forName(String name, boolean initialize, ClassLoader loader)570 public static Class<?> forName(String name, boolean initialize, 571 ClassLoader loader) 572 throws ClassNotFoundException 573 { 574 // Android-changed: Android has no SecurityManager. 575 /* 576 Class<?> caller = null; 577 @SuppressWarnings("removal") 578 SecurityManager sm = System.getSecurityManager(); 579 if (sm != null) { 580 // Reflective call to get caller class is only needed if a security manager 581 // is present. Avoid the overhead of making this call otherwise. 582 caller = Reflection.getCallerClass(); 583 if (loader == null) { 584 ClassLoader ccl = ClassLoader.getClassLoader(caller); 585 if (ccl != null) { 586 sm.checkPermission( 587 SecurityConstants.GET_CLASSLOADER_PERMISSION); 588 } 589 } 590 } 591 */ 592 if (loader == null) { 593 loader = BootClassLoader.getInstance(); 594 } 595 Class<?> result; 596 try { 597 result = classForName(name, initialize, loader); 598 } catch (ClassNotFoundException e) { 599 Throwable cause = e.getCause(); 600 if (cause instanceof LinkageError) { 601 throw (LinkageError) cause; 602 } 603 throw e; 604 } 605 return result; 606 } 607 608 /** Called after security checks have been made. */ 609 @FastNative classForName(String className, boolean shouldInitialize, ClassLoader classLoader)610 static native Class<?> classForName(String className, boolean shouldInitialize, 611 ClassLoader classLoader) throws ClassNotFoundException; 612 613 // Android-removed: Remove unsupported forName(Module, String) method. 614 /* 615 * Returns the {@code Class} with the given <a href="ClassLoader.html#name"> 616 * binary name</a> in the given module. 617 * 618 * <p> This method attempts to locate and load the class or interface. 619 * It does not link the class, and does not run the class initializer. 620 * If the class is not found, this method returns {@code null}. </p> 621 * 622 * <p> If the class loader of the given module defines other modules and 623 * the given name is a class defined in a different module, this method 624 * returns {@code null} after the class is loaded. </p> 625 * 626 * <p> This method does not check whether the requested class is 627 * accessible to its caller. </p> 628 * 629 * @apiNote 630 * This method returns {@code null} on failure rather than 631 * throwing a {@link ClassNotFoundException}, as is done by 632 * the {@link #forName(String, boolean, ClassLoader)} method. 633 * The security check is a stack-based permission check if the caller 634 * loads a class in another module. 635 * 636 * @param module A module 637 * @param name The <a href="ClassLoader.html#binary-name">binary name</a> 638 * of the class 639 * @return {@code Class} object of the given name defined in the given module; 640 * {@code null} if not found. 641 * 642 * @throws NullPointerException if the given module or name is {@code null} 643 * 644 * @throws LinkageError if the linkage fails 645 * 646 * @throws SecurityException 647 * <ul> 648 * <li> if the caller is not the specified module and 649 * {@code RuntimePermission("getClassLoader")} permission is denied; or</li> 650 * <li> access to the module content is denied. For example, 651 * permission check will be performed when a class loader calls 652 * {@link ModuleReader#open(String)} to read the bytes of a class file 653 * in a module.</li> 654 * </ul> 655 * 656 * @jls 12.2 Loading of Classes and Interfaces 657 * @jls 12.3 Linking of Classes and Interfaces 658 * @since 9 659 * @spec JPMS 660 * 661 @CallerSensitive 662 public static Class<?> forName(Module module, String name) { 663 Objects.requireNonNull(module); 664 Objects.requireNonNull(name); 665 666 ClassLoader cl; 667 SecurityManager sm = System.getSecurityManager(); 668 if (sm != null) { 669 Class<?> caller = Reflection.getCallerClass(); 670 if (caller != null && caller.getModule() != module) { 671 // if caller is null, Class.forName is the last java frame on the stack. 672 // java.base has all permissions 673 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION); 674 } 675 PrivilegedAction<ClassLoader> pa = module::getClassLoader; 676 cl = AccessController.doPrivileged(pa); 677 } else { 678 cl = module.getClassLoader(); 679 } 680 681 if (cl != null) { 682 return cl.loadClass(module, name); 683 } else { 684 return BootLoader.loadClass(module, name); 685 } 686 } 687 */ 688 689 // Android-changed: Remove SecurityException javadoc. 690 /** 691 * Creates a new instance of the class represented by this {@code Class} 692 * object. The class is instantiated as if by a {@code new} 693 * expression with an empty argument list. The class is initialized if it 694 * has not already been initialized. 695 * 696 * @deprecated This method propagates any exception thrown by the 697 * nullary constructor, including a checked exception. Use of 698 * this method effectively bypasses the compile-time exception 699 * checking that would otherwise be performed by the compiler. 700 * The {@link 701 * java.lang.reflect.Constructor#newInstance(java.lang.Object...) 702 * Constructor.newInstance} method avoids this problem by wrapping 703 * any exception thrown by the constructor in a (checked) {@link 704 * java.lang.reflect.InvocationTargetException}. 705 * 706 * <p>The call 707 * 708 * <pre>{@code 709 * clazz.newInstance() 710 * }</pre> 711 * 712 * can be replaced by 713 * 714 * <pre>{@code 715 * clazz.getDeclaredConstructor().newInstance() 716 * }</pre> 717 * 718 * The latter sequence of calls is inferred to be able to throw 719 * the additional exception types {@link 720 * InvocationTargetException} and {@link 721 * NoSuchMethodException}. Both of these exception types are 722 * subclasses of {@link ReflectiveOperationException}. 723 * 724 * @return a newly allocated instance of the class represented by this 725 * object. 726 * @throws IllegalAccessException if the class or its nullary 727 * constructor is not accessible. 728 * @throws InstantiationException 729 * if this {@code Class} represents an abstract class, 730 * an interface, an array class, a primitive type, or void; 731 * or if the class has no nullary constructor; 732 * or if the instantiation fails for some other reason. 733 * @throws ExceptionInInitializerError if the initialization 734 * provoked by this method fails. 735 */ 736 // Android-changed: Implement newInstance() by native code. 737 /* 738 @SuppressWarnings("removal") 739 @CallerSensitive 740 public T newInstance() 741 throws InstantiationException, IllegalAccessException 742 { 743 SecurityManager sm = System.getSecurityManager(); 744 if (sm != null) { 745 checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), false); 746 } 747 748 // Constructor lookup 749 Constructor<T> tmpConstructor = cachedConstructor; 750 if (tmpConstructor == null) { 751 if (this == Class.class) { 752 throw new IllegalAccessException( 753 "Can not call newInstance() on the Class for java.lang.Class" 754 ); 755 } 756 try { 757 Class<?>[] empty = {}; 758 final Constructor<T> c = getReflectionFactory().copyConstructor( 759 getConstructor0(empty, Member.DECLARED)); 760 // Disable accessibility checks on the constructor 761 // access check is done with the true caller 762 java.security.AccessController.doPrivileged( 763 new java.security.PrivilegedAction<>() { 764 public Void run() { 765 c.setAccessible(true); 766 return null; 767 } 768 }); 769 cachedConstructor = tmpConstructor = c; 770 } catch (NoSuchMethodException e) { 771 throw (InstantiationException) 772 new InstantiationException(getName()).initCause(e); 773 } 774 } 775 776 try { 777 Class<?> caller = Reflection.getCallerClass(); 778 return getReflectionFactory().newInstance(tmpConstructor, null, caller); 779 } catch (InvocationTargetException e) { 780 Unsafe.getUnsafe().throwException(e.getTargetException()); 781 // Not reached 782 return null; 783 } 784 } 785 786 private transient volatile Constructor<T> cachedConstructor; 787 */ 788 @FastNative 789 @Deprecated(since="9") newInstance()790 public native T newInstance() throws InstantiationException, IllegalAccessException; 791 792 /** 793 * Determines if the specified {@code Object} is assignment-compatible 794 * with the object represented by this {@code Class}. This method is 795 * the dynamic equivalent of the Java language {@code instanceof} 796 * operator. The method returns {@code true} if the specified 797 * {@code Object} argument is non-null and can be cast to the 798 * reference type represented by this {@code Class} object without 799 * raising a {@code ClassCastException.} It returns {@code false} 800 * otherwise. 801 * 802 * <p> Specifically, if this {@code Class} object represents a 803 * declared class, this method returns {@code true} if the specified 804 * {@code Object} argument is an instance of the represented class (or 805 * of any of its subclasses); it returns {@code false} otherwise. If 806 * this {@code Class} object represents an array class, this method 807 * returns {@code true} if the specified {@code Object} argument 808 * can be converted to an object of the array class by an identity 809 * conversion or by a widening reference conversion; it returns 810 * {@code false} otherwise. If this {@code Class} object 811 * represents an interface, this method returns {@code true} if the 812 * class or any superclass of the specified {@code Object} argument 813 * implements this interface; it returns {@code false} otherwise. If 814 * this {@code Class} object represents a primitive type, this method 815 * returns {@code false}. 816 * 817 * @param obj the object to check 818 * @return true if {@code obj} is an instance of this class 819 * 820 * @since 1.1 821 */ 822 @IntrinsicCandidate 823 // Android-changed: JNI code can be replaced by simple java code. 824 // public native boolean isInstance(Object obj); isInstance(Object obj)825 public boolean isInstance(Object obj) { 826 if (obj == null) { 827 return false; 828 } 829 return isAssignableFrom(obj.getClass()); 830 } 831 832 833 /** 834 * Determines if the class or interface represented by this 835 * {@code Class} object is either the same as, or is a superclass or 836 * superinterface of, the class or interface represented by the specified 837 * {@code Class} parameter. It returns {@code true} if so; 838 * otherwise it returns {@code false}. If this {@code Class} 839 * object represents a primitive type, this method returns 840 * {@code true} if the specified {@code Class} parameter is 841 * exactly this {@code Class} object; otherwise it returns 842 * {@code false}. 843 * 844 * <p> Specifically, this method tests whether the type represented by the 845 * specified {@code Class} parameter can be converted to the type 846 * represented by this {@code Class} object via an identity conversion 847 * or via a widening reference conversion. See <cite>The Java Language 848 * Specification</cite>, sections {@jls 5.1.1} and {@jls 5.1.4}, 849 * for details. 850 * 851 * @param cls the {@code Class} object to be checked 852 * @return the {@code boolean} value indicating whether objects of the 853 * type {@code cls} can be assigned to objects of this class 854 * @throws NullPointerException if the specified Class parameter is 855 * null. 856 * @since 1.1 857 */ 858 @IntrinsicCandidate 859 // Android-changed: JNI code can be replaced by simple java code. 860 // public native boolean isAssignableFrom(Class<?> cls); isAssignableFrom(Class<?> cls)861 public boolean isAssignableFrom(Class<?> cls) { 862 if (this == cls) { 863 return true; // Can always assign to things of the same type. 864 } else if (this == Object.class) { 865 return !cls.isPrimitive(); // Can assign any reference to java.lang.Object. 866 } else if (isArray()) { 867 return cls.isArray() && componentType.isAssignableFrom(cls.componentType); 868 } else if (isInterface()) { 869 // Search iftable which has a flattened and uniqued list of interfaces. 870 Object[] iftable = cls.ifTable; 871 if (iftable != null) { 872 for (int i = 0; i < iftable.length; i += 2) { 873 if (iftable[i] == this) { 874 return true; 875 } 876 } 877 } 878 return false; 879 } else { 880 if (!cls.isInterface()) { 881 for (cls = cls.superClass; cls != null; cls = cls.superClass) { 882 if (cls == this) { 883 return true; 884 } 885 } 886 } 887 return false; 888 } 889 } 890 891 /** 892 * Determines if this {@code Class} object represents an 893 * interface type. 894 * 895 * @return {@code true} if this {@code Class} object represents an interface; 896 * {@code false} otherwise. 897 */ 898 @IntrinsicCandidate 899 // Android-changed: JNI code can be replaced by simple java code. 900 // public native boolean isInterface(); isInterface()901 public boolean isInterface() { 902 return (accessFlags & Modifier.INTERFACE) != 0; 903 } 904 905 /** 906 * Determines if this {@code Class} object represents an array class. 907 * 908 * @return {@code true} if this {@code Class} object represents an array class; 909 * {@code false} otherwise. 910 * @since 1.1 911 */ 912 @IntrinsicCandidate 913 // Android-changed: JNI code can be replaced by simple java code. 914 // public native boolean isArray(); isArray()915 public boolean isArray() { 916 return getComponentType() != null; 917 } 918 919 /** 920 * Determines if the specified {@code Class} object represents a 921 * primitive type. 922 * 923 * <p> There are nine predefined {@code Class} objects to represent 924 * the eight primitive types and void. These are created by the Java 925 * Virtual Machine, and have the same names as the primitive types that 926 * they represent, namely {@code boolean}, {@code byte}, 927 * {@code char}, {@code short}, {@code int}, 928 * {@code long}, {@code float}, and {@code double}. 929 * 930 * <p> These objects may only be accessed via the following public static 931 * final variables, and are the only {@code Class} objects for which 932 * this method returns {@code true}. 933 * 934 * @return true if and only if this class represents a primitive type 935 * 936 * @see java.lang.Boolean#TYPE 937 * @see java.lang.Character#TYPE 938 * @see java.lang.Byte#TYPE 939 * @see java.lang.Short#TYPE 940 * @see java.lang.Integer#TYPE 941 * @see java.lang.Long#TYPE 942 * @see java.lang.Float#TYPE 943 * @see java.lang.Double#TYPE 944 * @see java.lang.Void#TYPE 945 * @since 1.1 946 */ 947 @IntrinsicCandidate 948 // Android-changed: JNI code can be replaced by simple java code. 949 // public native boolean isPrimitive(); isPrimitive()950 public boolean isPrimitive() { 951 return (primitiveType & 0xFFFF) != 0; 952 } 953 954 /** 955 * Indicates whether this {@code Class} or its parents override finalize. 956 * 957 * @return {@code true} if and if this class or its parents override 958 * finalize; 959 * 960 * @hide 961 */ isFinalizable()962 public boolean isFinalizable() { 963 return (getModifiers() & FINALIZABLE) != 0; 964 } 965 966 /** 967 * Returns true if this {@code Class} object represents an annotation 968 * interface. Note that if this method returns true, {@link #isInterface()} 969 * would also return true, as all annotation interfaces are also interfaces. 970 * 971 * @return {@code true} if this {@code Class} object represents an annotation 972 * interface; {@code false} otherwise 973 * @since 1.5 974 */ isAnnotation()975 public boolean isAnnotation() { 976 return (getModifiers() & ANNOTATION) != 0; 977 } 978 979 /** 980 *{@return {@code true} if and only if this class has the synthetic modifier 981 * bit set} 982 * 983 * @jls 13.1 The Form of a Binary 984 * @jvms 4.1 The {@code ClassFile} Structure 985 * @see <a 986 * href="{@docRoot}/java.base/java/lang/reflect/package-summary.html#LanguageJvmModel">Java 987 * programming language and JVM modeling in core reflection</a> 988 * @since 1.5 989 */ isSynthetic()990 public boolean isSynthetic() { 991 return (getModifiers() & SYNTHETIC) != 0; 992 } 993 994 // Android-changed: Removed javadoc related to hidden classes. 995 /** 996 * Returns the name of the entity (class, interface, array class, 997 * primitive type, or void) represented by this {@code Class} object. 998 * 999 * <p> If this {@code Class} object represents a class or interface, 1000 * not an array class, then: 1001 * 1002 * <p> If this {@code Class} object represents an array class, then 1003 * the result is a string consisting of one or more '{@code [}' characters 1004 * representing the depth of the array nesting, followed by the element 1005 * type as encoded using the following table: 1006 * 1007 * <blockquote><table class="striped"> 1008 * <caption style="display:none">Element types and encodings</caption> 1009 * <thead> 1010 * <tr><th scope="col"> Element Type <th scope="col"> Encoding 1011 * </thead> 1012 * <tbody style="text-align:left"> 1013 * <tr><th scope="row"> {@code boolean} <td style="text-align:center"> {@code Z} 1014 * <tr><th scope="row"> {@code byte} <td style="text-align:center"> {@code B} 1015 * <tr><th scope="row"> {@code char} <td style="text-align:center"> {@code C} 1016 * <tr><th scope="row"> class or interface with <a href="ClassLoader.html#binary-name">binary name</a> <i>N</i> 1017 * <td style="text-align:center"> {@code L}<em>N</em>{@code ;} 1018 * <tr><th scope="row"> {@code double} <td style="text-align:center"> {@code D} 1019 * <tr><th scope="row"> {@code float} <td style="text-align:center"> {@code F} 1020 * <tr><th scope="row"> {@code int} <td style="text-align:center"> {@code I} 1021 * <tr><th scope="row"> {@code long} <td style="text-align:center"> {@code J} 1022 * <tr><th scope="row"> {@code short} <td style="text-align:center"> {@code S} 1023 * </tbody> 1024 * </table></blockquote> 1025 * 1026 * <p> If this {@code Class} object represents a primitive type or {@code void}, 1027 * then the result is a string with the same spelling as the Java language 1028 * keyword which corresponds to the primitive type or {@code void}. 1029 * 1030 * <p> Examples: 1031 * <blockquote><pre> 1032 * String.class.getName() 1033 * returns "java.lang.String" 1034 * byte.class.getName() 1035 * returns "byte" 1036 * (new Object[3]).getClass().getName() 1037 * returns "[Ljava.lang.Object;" 1038 * (new int[3][4][5][6][7][8][9]).getClass().getName() 1039 * returns "[[[[[[[I" 1040 * </pre></blockquote> 1041 * 1042 * @return the name of the class, interface, or other entity 1043 * represented by this {@code Class} object. 1044 * @jls 13.1 The Form of a Binary 1045 */ getName()1046 public String getName() { 1047 String name = this.name; 1048 // Android-changed: ART has a different JNI layer. 1049 // return name != null ? name : initClassName(); 1050 if (name == null) 1051 this.name = name = getNameNative(); 1052 return name; 1053 1054 } 1055 1056 // Android-changed: ART has a different JNI layer. 1057 // private native String initClassName(); 1058 @FastNative getNameNative()1059 private native String getNameNative(); 1060 1061 // Android-changed: Remove SecurityException javadoc. 1062 /** 1063 * Returns the class loader for the class. Some implementations may use 1064 * null to represent the bootstrap class loader. This method will return 1065 * null in such implementations if this class was loaded by the bootstrap 1066 * class loader. 1067 * 1068 * <p>If this {@code Class} object 1069 * represents a primitive type or void, null is returned. 1070 * 1071 * @return the class loader that loaded the class or interface 1072 * represented by this {@code Class} object. 1073 * @see java.lang.ClassLoader 1074 * @see SecurityManager#checkPermission 1075 * @see java.lang.RuntimePermission 1076 */ 1077 // Android-changed: Remove unused annotation. 1078 // @CallerSensitive 1079 // @ForceInline // to ensure Reflection.getCallerClass optimization getClassLoader()1080 public ClassLoader getClassLoader() { 1081 if (isPrimitive()) { 1082 return null; 1083 } 1084 // Android-note: The RI returns null in the case where Android returns BootClassLoader. 1085 // Noted in http://b/111850480#comment3 1086 return (classLoader == null) ? BootClassLoader.getInstance() : classLoader; 1087 } 1088 1089 // Android-removed: Remove unsupported getModule(). 1090 /* 1091 * Returns the module that this class or interface is a member of. 1092 * 1093 * If this class represents an array type then this method returns the 1094 * {@code Module} for the element type. If this class represents a 1095 * primitive type or void, then the {@code Module} object for the 1096 * {@code java.base} module is returned. 1097 * 1098 * If this class is in an unnamed module then the {@linkplain 1099 * ClassLoader#getUnnamedModule() unnamed} {@code Module} of the class 1100 * loader for this class is returned. 1101 * 1102 * @return the module that this class or interface is a member of 1103 * 1104 * @since 9 1105 * @spec JPMS 1106 * 1107 public Module getModule() { 1108 return module; 1109 } 1110 1111 // set by VM 1112 private transient Module module; 1113 1114 // Set by VM 1115 private transient Object classData; 1116 1117 // package-private 1118 Object getClassData() { 1119 return classData; 1120 } 1121 */ 1122 1123 /** 1124 * Returns an array of {@code TypeVariable} objects that represent the 1125 * type variables declared by the generic declaration represented by this 1126 * {@code GenericDeclaration} object, in declaration order. Returns an 1127 * array of length 0 if the underlying generic declaration declares no type 1128 * variables. 1129 * 1130 * @return an array of {@code TypeVariable} objects that represent 1131 * the type variables declared by this generic declaration 1132 * @throws java.lang.reflect.GenericSignatureFormatError if the generic 1133 * signature of this generic declaration does not conform to 1134 * the format specified in section {@jvms 4.7.9} of 1135 * <cite>The Java Virtual Machine Specification</cite> 1136 * @since 1.5 1137 */ 1138 @Override getTypeParameters()1139 public synchronized TypeVariable<Class<T>>[] getTypeParameters() { 1140 String annotationSignature = getSignatureAttribute(); 1141 if (annotationSignature == null) { 1142 return EmptyArray.TYPE_VARIABLE; 1143 } 1144 GenericSignatureParser parser = new GenericSignatureParser(getClassLoader()); 1145 parser.parseForClass(this, annotationSignature); 1146 return parser.formalTypeParameters; 1147 } 1148 1149 1150 /** 1151 * Returns the {@code Class} representing the direct superclass of the 1152 * entity (class, interface, primitive type or void) represented by 1153 * this {@code Class}. If this {@code Class} represents either the 1154 * {@code Object} class, an interface, a primitive type, or void, then 1155 * null is returned. If this {@code Class} object represents an array class 1156 * then the {@code Class} object representing the {@code Object} class is 1157 * returned. 1158 * 1159 * @return the direct superclass of the class represented by this {@code Class} object 1160 */ 1161 @IntrinsicCandidate 1162 // Android-changed: ART has a different JNI layer. 1163 // public native Class<? super T> getSuperclass(); getSuperclass()1164 public Class<? super T> getSuperclass() { 1165 // For interfaces superClass is Object (which agrees with the JNI spec) 1166 // but not with the expected behavior here. 1167 if (isInterface()) { 1168 return null; 1169 } else { 1170 return superClass; 1171 } 1172 } 1173 1174 /** 1175 * Returns the {@code Type} representing the direct superclass of 1176 * the entity (class, interface, primitive type or void) represented by 1177 * this {@code Class} object. 1178 * 1179 * <p>If the superclass is a parameterized type, the {@code Type} 1180 * object returned must accurately reflect the actual type 1181 * arguments used in the source code. The parameterized type 1182 * representing the superclass is created if it had not been 1183 * created before. See the declaration of {@link 1184 * java.lang.reflect.ParameterizedType ParameterizedType} for the 1185 * semantics of the creation process for parameterized types. If 1186 * this {@code Class} object represents either the {@code Object} 1187 * class, an interface, a primitive type, or void, then null is 1188 * returned. If this {@code Class} object represents an array class 1189 * then the {@code Class} object representing the {@code Object} class is 1190 * returned. 1191 * 1192 * @throws java.lang.reflect.GenericSignatureFormatError if the generic 1193 * class signature does not conform to the format specified in 1194 * section {@jvms 4.7.9} of <cite>The Java Virtual 1195 * Machine Specification</cite> 1196 * @throws TypeNotPresentException if the generic superclass 1197 * refers to a non-existent type declaration 1198 * @throws java.lang.reflect.MalformedParameterizedTypeException if the 1199 * generic superclass refers to a parameterized type that cannot be 1200 * instantiated for any reason 1201 * @return the direct superclass of the class represented by this {@code Class} object 1202 * @since 1.5 1203 */ getGenericSuperclass()1204 public Type getGenericSuperclass() { 1205 Type genericSuperclass = getSuperclass(); 1206 // This method is specified to return null for all cases where getSuperclass 1207 // returns null, i.e, for primitives, interfaces, void and java.lang.Object. 1208 if (genericSuperclass == null) { 1209 return null; 1210 } 1211 1212 String annotationSignature = getSignatureAttribute(); 1213 if (annotationSignature != null) { 1214 GenericSignatureParser parser = new GenericSignatureParser(getClassLoader()); 1215 parser.parseForClass(this, annotationSignature); 1216 genericSuperclass = parser.superclassType; 1217 } 1218 return Types.getType(genericSuperclass); 1219 } 1220 1221 /** 1222 * Gets the package of this class. 1223 * 1224 * <p>If this class represents an array type, a primitive type or void, 1225 * this method returns {@code null}. 1226 * 1227 * @return the package of this class. 1228 * @revised 9 1229 */ getPackage()1230 public Package getPackage() { 1231 // Android-changed: ART has a different JNI layer. 1232 /* 1233 if (isPrimitive() || isArray()) { 1234 return null; 1235 } 1236 ClassLoader cl = getClassLoader0(); 1237 return cl != null ? cl.definePackage(this) 1238 : BootLoader.definePackage(this); 1239 */ 1240 ClassLoader loader = getClassLoader(); 1241 if (loader != null) { 1242 String packageName = getPackageName(); 1243 return packageName != null ? loader.getPackage(packageName) : null; 1244 } 1245 return null; 1246 } 1247 1248 /** 1249 * Returns the fully qualified package name. 1250 * 1251 * <p> If this class is a top level class, then this method returns the fully 1252 * qualified name of the package that the class is a member of, or the 1253 * empty string if the class is in an unnamed package. 1254 * 1255 * <p> If this class is a member class, then this method is equivalent to 1256 * invoking {@code getPackageName()} on the {@linkplain #getEnclosingClass 1257 * enclosing class}. 1258 * 1259 * <p> If this class is a {@linkplain #isLocalClass local class} or an {@linkplain 1260 * #isAnonymousClass() anonymous class}, then this method is equivalent to 1261 * invoking {@code getPackageName()} on the {@linkplain #getDeclaringClass 1262 * declaring class} of the {@linkplain #getEnclosingMethod enclosing method} or 1263 * {@linkplain #getEnclosingConstructor enclosing constructor}. 1264 * 1265 * <p> If this class represents an array type then this method returns the 1266 * package name of the element type. If this class represents a primitive 1267 * type or void then the package name "{@code java.lang}" is returned. 1268 * 1269 * @return the fully qualified package name 1270 * 1271 * @since 9 1272 * @jls 6.7 Fully Qualified Names 1273 */ getPackageName()1274 public String getPackageName() { 1275 // BEGIN Android-changed: Don't use a private field as a cache. 1276 /* 1277 String pn = this.packageName; 1278 if (pn == null) { 1279 Class<?> c = isArray() ? elementType() : this; 1280 if (c.isPrimitive()) { 1281 pn = "java.lang"; 1282 } else { 1283 String cn = c.getName(); 1284 int dot = cn.lastIndexOf('.'); 1285 pn = (dot != -1) ? cn.substring(0, dot).intern() : ""; 1286 } 1287 this.packageName = pn; 1288 } 1289 return pn; 1290 */ 1291 Class<?> c = this; 1292 while (c.isArray()) { 1293 c = c.getComponentType(); 1294 } 1295 if (c.isPrimitive()) { 1296 return "java.lang"; 1297 } else { 1298 String cn = c.getName(); 1299 int dot = cn.lastIndexOf('.'); 1300 return (dot != -1) ? cn.substring(0, dot).intern() : ""; 1301 } 1302 // END Android-changed: Don't use a private field as a cache. 1303 } 1304 1305 // cached package name 1306 // Android-removed: Don't use a private field as a cache. 1307 // private transient String packageName; 1308 1309 /** 1310 * Returns the interfaces directly implemented by the class or interface 1311 * represented by this {@code Class} object. 1312 * 1313 * <p>If this {@code Class} object represents a class, the return value is an array 1314 * containing objects representing all interfaces directly implemented by 1315 * the class. The order of the interface objects in the array corresponds 1316 * to the order of the interface names in the {@code implements} clause of 1317 * the declaration of the class represented by this {@code Class} object. For example, 1318 * given the declaration: 1319 * <blockquote> 1320 * {@code class Shimmer implements FloorWax, DessertTopping { ... }} 1321 * </blockquote> 1322 * suppose the value of {@code s} is an instance of 1323 * {@code Shimmer}; the value of the expression: 1324 * <blockquote> 1325 * {@code s.getClass().getInterfaces()[0]} 1326 * </blockquote> 1327 * is the {@code Class} object that represents interface 1328 * {@code FloorWax}; and the value of: 1329 * <blockquote> 1330 * {@code s.getClass().getInterfaces()[1]} 1331 * </blockquote> 1332 * is the {@code Class} object that represents interface 1333 * {@code DessertTopping}. 1334 * 1335 * <p>If this {@code Class} object represents an interface, the array contains objects 1336 * representing all interfaces directly extended by the interface. The 1337 * order of the interface objects in the array corresponds to the order of 1338 * the interface names in the {@code extends} clause of the declaration of 1339 * the interface represented by this {@code Class} object. 1340 * 1341 * <p>If this {@code Class} object represents a class or interface that implements no 1342 * interfaces, the method returns an array of length 0. 1343 * 1344 * <p>If this {@code Class} object represents a primitive type or void, the method 1345 * returns an array of length 0. 1346 * 1347 * <p>If this {@code Class} object represents an array type, the 1348 * interfaces {@code Cloneable} and {@code java.io.Serializable} are 1349 * returned in that order. 1350 * 1351 * @return an array of interfaces directly implemented by this class 1352 */ getInterfaces()1353 public Class<?>[] getInterfaces() { 1354 // Android-changed: ART has a different implenmentation. 1355 // return getInterfaces(true); 1356 if (isArray()) { 1357 return new Class<?>[] { Cloneable.class, Serializable.class }; 1358 } 1359 1360 final Class<?>[] ifaces = getInterfacesInternal(); 1361 if (ifaces == null) { 1362 return EmptyArray.CLASS; 1363 } 1364 1365 return ifaces; 1366 } 1367 1368 // Android-revmoed: Remove unused getInterfaces(boolean) method. 1369 /* 1370 private Class<?>[] getInterfaces(boolean cloneArray) { 1371 ReflectionData<T> rd = reflectionData(); 1372 if (rd == null) { 1373 // no cloning required 1374 return getInterfaces0(); 1375 } else { 1376 Class<?>[] interfaces = rd.interfaces; 1377 if (interfaces == null) { 1378 interfaces = getInterfaces0(); 1379 rd.interfaces = interfaces; 1380 } 1381 // defensively copy if requested 1382 return cloneArray ? interfaces.clone() : interfaces; 1383 } 1384 } 1385 */ 1386 1387 @FastNative getInterfacesInternal()1388 private native Class<?>[] getInterfacesInternal(); 1389 1390 1391 /** 1392 * Returns the {@code Type}s representing the interfaces 1393 * directly implemented by the class or interface represented by 1394 * this {@code Class} object. 1395 * 1396 * <p>If a superinterface is a parameterized type, the 1397 * {@code Type} object returned for it must accurately reflect 1398 * the actual type arguments used in the source code. The 1399 * parameterized type representing each superinterface is created 1400 * if it had not been created before. See the declaration of 1401 * {@link java.lang.reflect.ParameterizedType ParameterizedType} 1402 * for the semantics of the creation process for parameterized 1403 * types. 1404 * 1405 * <p>If this {@code Class} object represents a class, the return value is an array 1406 * containing objects representing all interfaces directly implemented by 1407 * the class. The order of the interface objects in the array corresponds 1408 * to the order of the interface names in the {@code implements} clause of 1409 * the declaration of the class represented by this {@code Class} object. 1410 * 1411 * <p>If this {@code Class} object represents an interface, the array contains objects 1412 * representing all interfaces directly extended by the interface. The 1413 * order of the interface objects in the array corresponds to the order of 1414 * the interface names in the {@code extends} clause of the declaration of 1415 * the interface represented by this {@code Class} object. 1416 * 1417 * <p>If this {@code Class} object represents a class or interface that implements no 1418 * interfaces, the method returns an array of length 0. 1419 * 1420 * <p>If this {@code Class} object represents a primitive type or void, the method 1421 * returns an array of length 0. 1422 * 1423 * <p>If this {@code Class} object represents an array type, the 1424 * interfaces {@code Cloneable} and {@code java.io.Serializable} are 1425 * returned in that order. 1426 * 1427 * @throws java.lang.reflect.GenericSignatureFormatError 1428 * if the generic class signature does not conform to the 1429 * format specified in section {@jvms 4.7.9} of <cite>The 1430 * Java Virtual Machine Specification</cite> 1431 * @throws TypeNotPresentException if any of the generic 1432 * superinterfaces refers to a non-existent type declaration 1433 * @throws java.lang.reflect.MalformedParameterizedTypeException 1434 * if any of the generic superinterfaces refer to a parameterized 1435 * type that cannot be instantiated for any reason 1436 * @return an array of interfaces directly implemented by this class 1437 * @since 1.5 1438 */ getGenericInterfaces()1439 public Type[] getGenericInterfaces() { 1440 Type[] result; 1441 synchronized (Caches.genericInterfaces) { 1442 result = Caches.genericInterfaces.get(this); 1443 if (result == null) { 1444 String annotationSignature = getSignatureAttribute(); 1445 if (annotationSignature == null) { 1446 result = getInterfaces(); 1447 } else { 1448 GenericSignatureParser parser = new GenericSignatureParser(getClassLoader()); 1449 parser.parseForClass(this, annotationSignature); 1450 result = Types.getTypeArray(parser.interfaceTypes, false); 1451 } 1452 Caches.genericInterfaces.put(this, result); 1453 } 1454 } 1455 return (result.length == 0) ? result : result.clone(); 1456 } 1457 1458 1459 /** 1460 * Returns the {@code Class} representing the component type of an 1461 * array. If this class does not represent an array class this method 1462 * returns null. 1463 * 1464 * @return the {@code Class} representing the component type of this 1465 * class if this class is an array 1466 * @see java.lang.reflect.Array 1467 * @since 1.1 1468 */ getComponentType()1469 public Class<?> getComponentType() { 1470 // Android-changed: Android can return componentType field directly. 1471 /* 1472 if (isArray()) { 1473 return componentType; 1474 } else { 1475 return null; 1476 } 1477 */ 1478 return componentType; 1479 } 1480 1481 /* 1482 * Returns the {@code Class} representing the element type of an array class. 1483 * If this class does not represent an array class, then this method returns 1484 * {@code null}. 1485 */ elementType()1486 private Class<?> elementType() { 1487 if (!isArray()) return null; 1488 1489 Class<?> c = this; 1490 while (c.isArray()) { 1491 c = c.getComponentType(); 1492 } 1493 return c; 1494 } 1495 1496 /** 1497 * Returns the Java language modifiers for this class or interface, encoded 1498 * in an integer. The modifiers consist of the Java Virtual Machine's 1499 * constants for {@code public}, {@code protected}, 1500 * {@code private}, {@code final}, {@code static}, 1501 * {@code abstract} and {@code interface}; they should be decoded 1502 * using the methods of class {@code Modifier}. 1503 * 1504 * <p> If the underlying class is an array class, then its 1505 * {@code public}, {@code private} and {@code protected} 1506 * modifiers are the same as those of its component type. If this 1507 * {@code Class} object represents a primitive type or void, its 1508 * {@code public} modifier is always {@code true}, and its 1509 * {@code protected} and {@code private} modifiers are always 1510 * {@code false}. If this {@code Class} object represents an array class, a 1511 * primitive type or void, then its {@code final} modifier is always 1512 * {@code true} and its interface modifier is always 1513 * {@code false}. The values of its other modifiers are not determined 1514 * by this specification. 1515 * 1516 * <p> The modifier encodings are defined in section {@jvms 4.1} 1517 * of <cite>The Java Virtual Machine Specification</cite>. 1518 * 1519 * @return the {@code int} representing the modifiers for this class 1520 * @see java.lang.reflect.Modifier 1521 * @see <a 1522 * href="{@docRoot}/java.base/java/lang/reflect/package-summary.html#LanguageJvmModel">Java 1523 * programming language and JVM modeling in core reflection</a> 1524 * @since 1.1 1525 * @jls 8.1.1 Class Modifiers 1526 * @jls 9.1.1. Interface Modifiers 1527 */ 1528 @IntrinsicCandidate 1529 // Android-changed: Android can use a simple java implementation. 1530 // public native int getModifiers(); getModifiers()1531 public int getModifiers() { 1532 // Array classes inherit modifiers from their component types, but in the case of arrays 1533 // of an inner class, the class file may contain "fake" access flags because it's not valid 1534 // for a top-level class to private, say. The real access flags are stored in the InnerClass 1535 // attribute, so we need to make sure we drill down to the inner class: the accessFlags 1536 // field is not the value we want to return, and the synthesized array class does not itself 1537 // have an InnerClass attribute. https://code.google.com/p/android/issues/detail?id=56267 1538 if (isArray()) { 1539 int componentModifiers = getComponentType().getModifiers(); 1540 if ((componentModifiers & Modifier.INTERFACE) != 0) { 1541 componentModifiers &= ~(Modifier.INTERFACE | Modifier.STATIC); 1542 } 1543 return Modifier.ABSTRACT | Modifier.FINAL | componentModifiers; 1544 } 1545 int JAVA_FLAGS_MASK = 0xffff; 1546 int modifiers = this.getInnerClassFlags(accessFlags & JAVA_FLAGS_MASK); 1547 return modifiers & JAVA_FLAGS_MASK; 1548 } 1549 1550 /** 1551 * Gets the signers of this class. 1552 * 1553 * @return the signers of this class, or null if there are no signers. In 1554 * particular, this method returns null if this {@code Class} object represents 1555 * a primitive type or void. 1556 * @since 1.1 1557 */ getSigners()1558 public Object[] getSigners() { 1559 return null; 1560 } 1561 1562 @FastNative getEnclosingMethodNative()1563 private native Method getEnclosingMethodNative(); 1564 1565 /** 1566 * If this {@code Class} object represents a local or anonymous 1567 * class within a method, returns a {@link 1568 * java.lang.reflect.Method Method} object representing the 1569 * immediately enclosing method of the underlying class. Returns 1570 * {@code null} otherwise. 1571 * 1572 * In particular, this method returns {@code null} if the underlying 1573 * class is a local or anonymous class immediately enclosed by a class or 1574 * interface declaration, instance initializer or static initializer. 1575 * 1576 * @return the immediately enclosing method of the underlying class, if 1577 * that class is a local or anonymous class; otherwise {@code null}. 1578 * @since 1.5 1579 */ 1580 // Android-changed: Removed SecurityException. getEnclosingMethod()1581 public Method getEnclosingMethod() { 1582 if (classNameImpliesTopLevel()) { 1583 return null; 1584 } 1585 /* 1586 else { 1587 if (!enclosingInfo.isMethod()) 1588 return null; 1589 1590 MethodRepository typeInfo = MethodRepository.make(enclosingInfo.getDescriptor(), 1591 getFactory()); 1592 Class<?> returnType = toClass(typeInfo.getReturnType()); 1593 Type [] parameterTypes = typeInfo.getParameterTypes(); 1594 Class<?>[] parameterClasses = new Class<?>[parameterTypes.length]; 1595 1596 // Convert Types to Classes; returned types *should* 1597 // be class objects since the methodDescriptor's used 1598 // don't have generics information 1599 for(int i = 0; i < parameterClasses.length; i++) 1600 parameterClasses[i] = toClass(parameterTypes[i]); 1601 1602 // Perform access check 1603 final Class<?> enclosingCandidate = enclosingInfo.getEnclosingClass(); 1604 @SuppressWarnings("removal") 1605 SecurityManager sm = System.getSecurityManager(); 1606 if (sm != null) { 1607 enclosingCandidate.checkMemberAccess(sm, Member.DECLARED, 1608 Reflection.getCallerClass(), true); 1609 } 1610 Method[] candidates = enclosingCandidate.privateGetDeclaredMethods(false); 1611 1612 /* 1613 * Loop over all declared methods; match method name, 1614 * number of and type of parameters, *and* return 1615 * type. Matching return type is also necessary 1616 * because of covariant returns, etc. 1617 * 1618 ReflectionFactory fact = getReflectionFactory(); 1619 for (Method m : candidates) { 1620 if (m.getName().equals(enclosingInfo.getName()) && 1621 arrayContentsEq(parameterClasses, 1622 fact.getExecutableSharedParameterTypes(m))) { 1623 // finally, check return type 1624 if (m.getReturnType().equals(returnType)) { 1625 return fact.copyMethod(m); 1626 } 1627 } 1628 } 1629 1630 throw new InternalError("Enclosing method not found"); 1631 } 1632 */ 1633 return getEnclosingMethodNative(); 1634 } 1635 1636 // Android-removed: Remove unused getEnclosingMethodInfo(). 1637 /* 1638 private native Object[] getEnclosingMethod0(); 1639 1640 private EnclosingMethodInfo getEnclosingMethodInfo() { 1641 Object[] enclosingInfo = getEnclosingMethod0(); 1642 if (enclosingInfo == null) 1643 return null; 1644 else { 1645 return new EnclosingMethodInfo(enclosingInfo); 1646 } 1647 } 1648 1649 private static final class EnclosingMethodInfo { 1650 private final Class<?> enclosingClass; 1651 private final String name; 1652 private final String descriptor; 1653 1654 static void validate(Object[] enclosingInfo) { 1655 if (enclosingInfo.length != 3) 1656 throw new InternalError("Malformed enclosing method information"); 1657 try { 1658 // The array is expected to have three elements: 1659 1660 // the immediately enclosing class 1661 Class<?> enclosingClass = (Class<?>)enclosingInfo[0]; 1662 assert(enclosingClass != null); 1663 1664 // the immediately enclosing method or constructor's 1665 // name (can be null). 1666 String name = (String)enclosingInfo[1]; 1667 1668 // the immediately enclosing method or constructor's 1669 // descriptor (null iff name is). 1670 String descriptor = (String)enclosingInfo[2]; 1671 assert((name != null && descriptor != null) || name == descriptor); 1672 } catch (ClassCastException cce) { 1673 throw new InternalError("Invalid type in enclosing method information", cce); 1674 } 1675 } 1676 1677 EnclosingMethodInfo(Object[] enclosingInfo) { 1678 validate(enclosingInfo); 1679 this.enclosingClass = (Class<?>)enclosingInfo[0]; 1680 this.name = (String)enclosingInfo[1]; 1681 this.descriptor = (String)enclosingInfo[2]; 1682 } 1683 1684 boolean isPartial() { 1685 return enclosingClass == null || name == null || descriptor == null; 1686 } 1687 1688 boolean isConstructor() { return !isPartial() && "<init>".equals(name); } 1689 1690 boolean isMethod() { return !isPartial() && !isConstructor() && !"<clinit>".equals(name); } 1691 1692 Class<?> getEnclosingClass() { return enclosingClass; } 1693 1694 String getName() { return name; } 1695 1696 String getDescriptor() { return descriptor; } 1697 1698 } 1699 1700 private static Class<?> toClass(Type o) { 1701 if (o instanceof GenericArrayType) 1702 return Array.newInstance(toClass(((GenericArrayType)o).getGenericComponentType()), 1703 0) 1704 .getClass(); 1705 return (Class<?>)o; 1706 } 1707 */ 1708 1709 /** 1710 * If this {@code Class} object represents a local or anonymous 1711 * class within a constructor, returns a {@link 1712 * java.lang.reflect.Constructor Constructor} object representing 1713 * the immediately enclosing constructor of the underlying 1714 * class. Returns {@code null} otherwise. In particular, this 1715 * method returns {@code null} if the underlying class is a local 1716 * or anonymous class immediately enclosed by a class or 1717 * interface declaration, instance initializer or static initializer. 1718 * 1719 * @return the immediately enclosing constructor of the underlying class, if 1720 * that class is a local or anonymous class; otherwise {@code null}. 1721 * @since 1.5 1722 */ 1723 // Android-changed: Removed SecurityException. getEnclosingConstructor()1724 public Constructor<?> getEnclosingConstructor() { 1725 if (classNameImpliesTopLevel()) { 1726 return null; 1727 } 1728 /* 1729 else { 1730 if (!enclosingInfo.isConstructor()) 1731 return null; 1732 1733 ConstructorRepository typeInfo = ConstructorRepository.make(enclosingInfo.getDescriptor(), 1734 getFactory()); 1735 Type [] parameterTypes = typeInfo.getParameterTypes(); 1736 Class<?>[] parameterClasses = new Class<?>[parameterTypes.length]; 1737 1738 // Convert Types to Classes; returned types *should* 1739 // be class objects since the methodDescriptor's used 1740 // don't have generics information 1741 for(int i = 0; i < parameterClasses.length; i++) 1742 parameterClasses[i] = toClass(parameterTypes[i]); 1743 1744 // Perform access check 1745 final Class<?> enclosingCandidate = enclosingInfo.getEnclosingClass(); 1746 @SuppressWarnings("removal") 1747 SecurityManager sm = System.getSecurityManager(); 1748 if (sm != null) { 1749 enclosingCandidate.checkMemberAccess(sm, Member.DECLARED, 1750 Reflection.getCallerClass(), true); 1751 } 1752 1753 Constructor<?>[] candidates = enclosingCandidate 1754 .privateGetDeclaredConstructors(false); 1755 /* 1756 * Loop over all declared constructors; match number 1757 * of and type of parameters. 1758 * 1759 ReflectionFactory fact = getReflectionFactory(); 1760 for (Constructor<?> c : candidates) { 1761 if (arrayContentsEq(parameterClasses, 1762 fact.getExecutableSharedParameterTypes(c))) { 1763 return fact.copyConstructor(c); 1764 } 1765 } 1766 1767 throw new InternalError("Enclosing constructor not found"); 1768 1769 } 1770 */ 1771 return getEnclosingConstructorNative(); 1772 } 1773 1774 @FastNative getEnclosingConstructorNative()1775 private native Constructor<?> getEnclosingConstructorNative(); 1776 classNameImpliesTopLevel()1777 private boolean classNameImpliesTopLevel() { 1778 return !getName().contains("$"); 1779 } 1780 1781 1782 /** 1783 * If the class or interface represented by this {@code Class} object 1784 * is a member of another class, returns the {@code Class} object 1785 * representing the class in which it was declared. This method returns 1786 * null if this class or interface is not a member of any other class. If 1787 * this {@code Class} object represents an array class, a primitive 1788 * type, or void,then this method returns null. 1789 * 1790 * @return the declaring class for this class 1791 * @since 1.1 1792 */ 1793 // Android-changed: Removed SecurityException. 1794 /* 1795 @CallerSensitive 1796 public Class<?> getDeclaringClass() throws SecurityException { 1797 final Class<?> candidate = getDeclaringClass0(); 1798 1799 if (candidate != null) { 1800 @SuppressWarnings("removal") 1801 SecurityManager sm = System.getSecurityManager(); 1802 if (sm != null) { 1803 candidate.checkPackageAccess(sm, 1804 ClassLoader.getClassLoader(Reflection.getCallerClass()), true); 1805 } 1806 } 1807 return candidate; 1808 } 1809 1810 private native Class<?> getDeclaringClass0(); 1811 */ 1812 @FastNative getDeclaringClass()1813 public native Class<?> getDeclaringClass(); 1814 1815 /** 1816 * Returns the immediately enclosing class of the underlying 1817 * class. If the underlying class is a top level class this 1818 * method returns {@code null}. 1819 * @return the immediately enclosing class of the underlying class 1820 * @since 1.5 1821 */ 1822 // Android-changed: Removed SecurityException. 1823 /* 1824 @CallerSensitive 1825 public Class<?> getEnclosingClass() throws SecurityException { 1826 // There are five kinds of classes (or interfaces): 1827 // a) Top level classes 1828 // b) Nested classes (static member classes) 1829 // c) Inner classes (non-static member classes) 1830 // d) Local classes (named classes declared within a method) 1831 // e) Anonymous classes 1832 1833 1834 // JVM Spec 4.7.7: A class must have an EnclosingMethod 1835 // attribute if and only if it is a local class or an 1836 // anonymous class. 1837 EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo(); 1838 Class<?> enclosingCandidate; 1839 1840 if (enclosingInfo == null) { 1841 // This is a top level or a nested class or an inner class (a, b, or c) 1842 enclosingCandidate = getDeclaringClass0(); 1843 } else { 1844 Class<?> enclosingClass = enclosingInfo.getEnclosingClass(); 1845 // This is a local class or an anonymous class (d or e) 1846 if (enclosingClass == this || enclosingClass == null) 1847 throw new InternalError("Malformed enclosing method information"); 1848 else 1849 enclosingCandidate = enclosingClass; 1850 } 1851 1852 if (enclosingCandidate != null) { 1853 @SuppressWarnings("removal") 1854 SecurityManager sm = System.getSecurityManager(); 1855 if (sm != null) { 1856 enclosingCandidate.checkPackageAccess(sm, 1857 ClassLoader.getClassLoader(Reflection.getCallerClass()), true); 1858 } 1859 } 1860 return enclosingCandidate; 1861 } 1862 */ 1863 @FastNative getEnclosingClass()1864 public native Class<?> getEnclosingClass(); 1865 1866 /** 1867 * Returns the simple name of the underlying class as given in the 1868 * source code. An empty string is returned if the underlying class is 1869 * {@linkplain #isAnonymousClass() anonymous}. 1870 * A {@linkplain #isSynthetic() synthetic class}, one not present 1871 * in source code, can have a non-empty name including special 1872 * characters, such as "{@code $}". 1873 * 1874 * <p>The simple name of an {@linkplain #isArray() array class} is the simple name of the 1875 * component type with "[]" appended. In particular the simple 1876 * name of an array class whose component type is anonymous is "[]". 1877 * 1878 * @return the simple name of the underlying class 1879 * @since 1.5 1880 */ getSimpleName()1881 public String getSimpleName() { 1882 // Android-changed: ART has a different JNI layer. 1883 if (isArray()) 1884 return getComponentType().getSimpleName()+"[]"; 1885 1886 return getSimpleNameNative(); 1887 } 1888 1889 /** 1890 * Return an informative string for the name of this class or interface. 1891 * 1892 * @return an informative string for the name of this class or interface 1893 * @since 1.8 1894 */ getTypeName()1895 public String getTypeName() { 1896 if (isArray()) { 1897 try { 1898 Class<?> cl = this; 1899 int dimensions = 0; 1900 do { 1901 dimensions++; 1902 cl = cl.getComponentType(); 1903 } while (cl.isArray()); 1904 return cl.getName() + "[]".repeat(dimensions); 1905 } catch (Throwable e) { /*FALLTHRU*/ } 1906 } 1907 return getName(); 1908 } 1909 1910 // Android-changed: Removed javadoc related to hidden classes. 1911 /** 1912 * Returns the canonical name of the underlying class as 1913 * defined by <cite>The Java Language Specification</cite>. 1914 * Returns {@code null} if the underlying class does not have a canonical 1915 * name. Classes without canonical names include: 1916 * <ul> 1917 * <li>a {@linkplain #isLocalClass() local class} 1918 * <li>a {@linkplain #isAnonymousClass() anonymous class} 1919 * <li>an array whose component type does not have a canonical name</li> 1920 * </ul> 1921 * 1922 * @return the canonical name of the underlying class if it exists, and 1923 * {@code null} otherwise. 1924 * @since 1.5 1925 */ getCanonicalName()1926 public String getCanonicalName() { 1927 // Android-changed: Android has no ReflectionData class. 1928 if (isArray()) { 1929 String canonicalName = getComponentType().getCanonicalName(); 1930 if (canonicalName != null) 1931 return canonicalName + "[]"; 1932 else 1933 return null; 1934 } 1935 if (isHidden() || isLocalOrAnonymousClass()) 1936 // Android-changed: Android has no ReflectionData class. Returns null directly. 1937 // return ReflectionData.NULL_SENTINEL; 1938 return null; 1939 Class<?> enclosingClass = getEnclosingClass(); 1940 if (enclosingClass == null) { // top level class 1941 return getName(); 1942 } else { 1943 String enclosingName = enclosingClass.getCanonicalName(); 1944 if (enclosingName == null) 1945 // Android-changed: Android has no ReflectionData class. Returns null directly. 1946 // return ReflectionData.NULL_SENTINEL; 1947 return null; 1948 String simpleName = getSimpleName(); 1949 return new StringBuilder(enclosingName.length() + simpleName.length() + 1) 1950 .append(enclosingName) 1951 .append('.') 1952 .append(simpleName) 1953 .toString(); 1954 } 1955 } 1956 1957 /** 1958 * Returns {@code true} if and only if the underlying class 1959 * is an anonymous class. 1960 * 1961 * @return {@code true} if and only if this class is an anonymous class. 1962 * @since 1.5 1963 * @jls 15.9.5 Anonymous Class Declarations 1964 */ 1965 // Android-changed: ART has a different JNI layer. 1966 /* 1967 public boolean isAnonymousClass() { 1968 return !isArray() && isLocalOrAnonymousClass() && 1969 getSimpleBinaryName0() == null; 1970 } 1971 */ 1972 @FastNative isAnonymousClass()1973 public native boolean isAnonymousClass(); 1974 1975 /** 1976 * Returns {@code true} if and only if the underlying class 1977 * is a local class. 1978 * 1979 * @return {@code true} if and only if this class is a local class. 1980 * @since 1.5 1981 * @jls 14.3 Local Class Declarations 1982 */ isLocalClass()1983 public boolean isLocalClass() { 1984 // Android-changed: ART has a different JNI layer. 1985 // return isLocalOrAnonymousClass() && 1986 // (isArray() || getSimpleBinaryName0() != null); 1987 return (getEnclosingMethod() != null || getEnclosingConstructor() != null) 1988 && !isAnonymousClass(); 1989 } 1990 1991 /** 1992 * Returns {@code true} if and only if the underlying class 1993 * is a member class. 1994 * 1995 * @return {@code true} if and only if this class is a member class. 1996 * @since 1.5 1997 * @jls 8.5 Member Type Declarations 1998 */ isMemberClass()1999 public boolean isMemberClass() { 2000 // Android-changed: ART has a different JNI layer. 2001 // return !isLocalOrAnonymousClass() && getDeclaringClass0() != null; 2002 return !isLocalOrAnonymousClass() && getDeclaringClass() != null; 2003 } 2004 2005 /** 2006 * Returns {@code true} if this is a top level class. Returns {@code false} 2007 * otherwise. 2008 */ isTopLevelClass()2009 private boolean isTopLevelClass() { 2010 // Android-changed: ART has a different JNI layer. 2011 // return !isLocalOrAnonymousClass() && getDeclaringClass0() == null; 2012 return !isLocalOrAnonymousClass() && getDeclaringClass() == null; 2013 } 2014 2015 /** 2016 * Returns {@code true} if this is a local class or an anonymous 2017 * class. Returns {@code false} otherwise. 2018 */ isLocalOrAnonymousClass()2019 private boolean isLocalOrAnonymousClass() { 2020 // Android-changed: ART has a different JNI layer. 2021 /* 2022 // JVM Spec 4.7.7: A class must have an EnclosingMethod 2023 // attribute if and only if it is a local class or an 2024 // anonymous class. 2025 return hasEnclosingMethodInfo(); 2026 */ 2027 return isLocalClass() || isAnonymousClass(); 2028 } 2029 2030 /** 2031 * Returns an array containing {@code Class} objects representing all 2032 * the public classes and interfaces that are members of the class 2033 * represented by this {@code Class} object. This includes public 2034 * class and interface members inherited from superclasses and public class 2035 * and interface members declared by the class. This method returns an 2036 * array of length 0 if this {@code Class} object has no public member 2037 * classes or interfaces. This method also returns an array of length 0 if 2038 * this {@code Class} object represents a primitive type, an array 2039 * class, or void. 2040 * 2041 * @return the array of {@code Class} objects representing the public 2042 * members of this class 2043 * 2044 * @since 1.1 2045 */ 2046 @SuppressWarnings("removal") 2047 @CallerSensitive getClasses()2048 public Class<?>[] getClasses() { 2049 // Android-changed: Removed SecurityManager check. 2050 List<Class<?>> result = new ArrayList<Class<?>>(); 2051 for (Class<?> c = this; c != null; c = c.superClass) { 2052 for (Class<?> member : c.getDeclaredClasses()) { 2053 if (Modifier.isPublic(member.getModifiers())) { 2054 result.add(member); 2055 } 2056 } 2057 } 2058 return result.toArray(new Class[result.size()]); 2059 } 2060 2061 2062 /** 2063 * Returns an array containing {@code Field} objects reflecting all 2064 * the accessible public fields of the class or interface represented by 2065 * this {@code Class} object. 2066 * 2067 * <p> If this {@code Class} object represents a class or interface with 2068 * no accessible public fields, then this method returns an array of length 2069 * 0. 2070 * 2071 * <p> If this {@code Class} object represents a class, then this method 2072 * returns the public fields of the class and of all its superclasses and 2073 * superinterfaces. 2074 * 2075 * <p> If this {@code Class} object represents an interface, then this 2076 * method returns the fields of the interface and of all its 2077 * superinterfaces. 2078 * 2079 * <p> If this {@code Class} object represents an array type, a primitive 2080 * type, or void, then this method returns an array of length 0. 2081 * 2082 * <p> The elements in the returned array are not sorted and are not in any 2083 * particular order. 2084 * 2085 * @return the array of {@code Field} objects representing the 2086 * public fields 2087 * @throws SecurityException 2088 * If a security manager, <i>s</i>, is present and 2089 * the caller's class loader is not the same as or an 2090 * ancestor of the class loader for the current class and 2091 * invocation of {@link SecurityManager#checkPackageAccess 2092 * s.checkPackageAccess()} denies access to the package 2093 * of this class. 2094 * 2095 * @since 1.1 2096 * @jls 8.2 Class Members 2097 * @jls 8.3 Field Declarations 2098 */ 2099 @CallerSensitive getFields()2100 public Field[] getFields() throws SecurityException { 2101 // Android-changed: Removed SecurityManager check. 2102 List<Field> fields = new ArrayList<Field>(); 2103 getPublicFieldsRecursive(fields); 2104 return fields.toArray(new Field[fields.size()]); 2105 } 2106 2107 /** 2108 * Populates {@code result} with public fields defined by this class, its 2109 * superclasses, and all implemented interfaces. 2110 */ getPublicFieldsRecursive(List<Field> result)2111 private void getPublicFieldsRecursive(List<Field> result) { 2112 // search superclasses 2113 for (Class<?> c = this; c != null; c = c.superClass) { 2114 Collections.addAll(result, c.getPublicDeclaredFields()); 2115 } 2116 2117 // search iftable which has a flattened and uniqued list of interfaces 2118 Object[] iftable = ifTable; 2119 if (iftable != null) { 2120 for (int i = 0; i < iftable.length; i += 2) { 2121 Collections.addAll(result, ((Class<?>) iftable[i]).getPublicDeclaredFields()); 2122 } 2123 } 2124 } 2125 2126 /** 2127 * Returns an array containing {@code Method} objects reflecting all the 2128 * public methods of the class or interface represented by this {@code 2129 * Class} object, including those declared by the class or interface and 2130 * those inherited from superclasses and superinterfaces. 2131 * 2132 * <p> If this {@code Class} object represents an array type, then the 2133 * returned array has a {@code Method} object for each of the public 2134 * methods inherited by the array type from {@code Object}. It does not 2135 * contain a {@code Method} object for {@code clone()}. 2136 * 2137 * <p> If this {@code Class} object represents an interface then the 2138 * returned array does not contain any implicitly declared methods from 2139 * {@code Object}. Therefore, if no methods are explicitly declared in 2140 * this interface or any of its superinterfaces then the returned array 2141 * has length 0. (Note that a {@code Class} object which represents a class 2142 * always has public methods, inherited from {@code Object}.) 2143 * 2144 * <p> The returned array never contains methods with names "{@code <init>}" 2145 * or "{@code <clinit>}". 2146 * 2147 * <p> The elements in the returned array are not sorted and are not in any 2148 * particular order. 2149 * 2150 * <p> Generally, the result is computed as with the following 4 step algorithm. 2151 * Let C be the class or interface represented by this {@code Class} object: 2152 * <ol> 2153 * <li> A union of methods is composed of: 2154 * <ol type="a"> 2155 * <li> C's declared public instance and static methods as returned by 2156 * {@link #getDeclaredMethods()} and filtered to include only public 2157 * methods.</li> 2158 * <li> If C is a class other than {@code Object}, then include the result 2159 * of invoking this algorithm recursively on the superclass of C.</li> 2160 * <li> Include the results of invoking this algorithm recursively on all 2161 * direct superinterfaces of C, but include only instance methods.</li> 2162 * </ol></li> 2163 * <li> Union from step 1 is partitioned into subsets of methods with same 2164 * signature (name, parameter types) and return type.</li> 2165 * <li> Within each such subset only the most specific methods are selected. 2166 * Let method M be a method from a set of methods with same signature 2167 * and return type. M is most specific if there is no such method 2168 * N != M from the same set, such that N is more specific than M. 2169 * N is more specific than M if: 2170 * <ol type="a"> 2171 * <li> N is declared by a class and M is declared by an interface; or</li> 2172 * <li> N and M are both declared by classes or both by interfaces and 2173 * N's declaring type is the same as or a subtype of M's declaring type 2174 * (clearly, if M's and N's declaring types are the same type, then 2175 * M and N are the same method).</li> 2176 * </ol></li> 2177 * <li> The result of this algorithm is the union of all selected methods from 2178 * step 3.</li> 2179 * </ol> 2180 * 2181 * @apiNote There may be more than one method with a particular name 2182 * and parameter types in a class because while the Java language forbids a 2183 * class to declare multiple methods with the same signature but different 2184 * return types, the Java virtual machine does not. This 2185 * increased flexibility in the virtual machine can be used to 2186 * implement various language features. For example, covariant 2187 * returns can be implemented with {@linkplain 2188 * java.lang.reflect.Method#isBridge bridge methods}; the bridge 2189 * method and the overriding method would have the same 2190 * signature but different return types. 2191 * 2192 * @return the array of {@code Method} objects representing the 2193 * public methods of this class 2194 * @throws SecurityException 2195 * If a security manager, <i>s</i>, is present and 2196 * the caller's class loader is not the same as or an 2197 * ancestor of the class loader for the current class and 2198 * invocation of {@link SecurityManager#checkPackageAccess 2199 * s.checkPackageAccess()} denies access to the package 2200 * of this class. 2201 * 2202 * @jls 8.2 Class Members 2203 * @jls 8.4 Method Declarations 2204 * @since 1.1 2205 */ 2206 @CallerSensitive getMethods()2207 public Method[] getMethods() throws SecurityException { 2208 // Android-changed: Removed SecurityManager check. 2209 List<Method> methods = new ArrayList<Method>(); 2210 getPublicMethodsInternal(methods); 2211 /* 2212 * Remove duplicate methods defined by superclasses and 2213 * interfaces, preferring to keep methods declared by derived 2214 * types. 2215 */ 2216 CollectionUtils.removeDuplicates(methods, Method.ORDER_BY_SIGNATURE); 2217 return methods.toArray(new Method[methods.size()]); 2218 } 2219 2220 /** 2221 * Populates {@code result} with public methods defined by this class, its 2222 * superclasses, and all implemented interfaces, including overridden methods. 2223 */ getPublicMethodsInternal(List<Method> result)2224 private void getPublicMethodsInternal(List<Method> result) { 2225 Collections.addAll(result, getDeclaredMethodsUnchecked(true)); 2226 if (!isInterface()) { 2227 // Search superclasses, for interfaces don't search java.lang.Object. 2228 for (Class<?> c = superClass; c != null; c = c.superClass) { 2229 Collections.addAll(result, c.getDeclaredMethodsUnchecked(true)); 2230 } 2231 } 2232 // Search iftable which has a flattened and uniqued list of interfaces. 2233 Object[] iftable = ifTable; 2234 if (iftable != null) { 2235 for (int i = 0; i < iftable.length; i += 2) { 2236 Class<?> ifc = (Class<?>) iftable[i]; 2237 Collections.addAll(result, ifc.getDeclaredMethodsUnchecked(true)); 2238 } 2239 } 2240 } 2241 2242 /** 2243 * Returns an array containing {@code Constructor} objects reflecting 2244 * all the public constructors of the class represented by this 2245 * {@code Class} object. An array of length 0 is returned if the 2246 * class has no public constructors, or if the class is an array class, or 2247 * if the class reflects a primitive type or void. 2248 * 2249 * @apiNote 2250 * While this method returns an array of {@code 2251 * Constructor<T>} objects (that is an array of constructors from 2252 * this class), the return type of this method is {@code 2253 * Constructor<?>[]} and <em>not</em> {@code Constructor<T>[]} as 2254 * might be expected. This less informative return type is 2255 * necessary since after being returned from this method, the 2256 * array could be modified to hold {@code Constructor} objects for 2257 * different classes, which would violate the type guarantees of 2258 * {@code Constructor<T>[]}. 2259 * 2260 * @return the array of {@code Constructor} objects representing the 2261 * public constructors of this class 2262 * @throws SecurityException 2263 * If a security manager, <i>s</i>, is present and 2264 * the caller's class loader is not the same as or an 2265 * ancestor of the class loader for the current class and 2266 * invocation of {@link SecurityManager#checkPackageAccess 2267 * s.checkPackageAccess()} denies access to the package 2268 * of this class. 2269 * 2270 * @since 1.1 2271 */ 2272 @CallerSensitive getConstructors()2273 public Constructor<?>[] getConstructors() throws SecurityException { 2274 // Android-changed: Removed SecurityManager check. 2275 return getDeclaredConstructorsInternal(true); 2276 } 2277 2278 2279 /** 2280 * Returns a {@code Field} object that reflects the specified public member 2281 * field of the class or interface represented by this {@code Class} 2282 * object. The {@code name} parameter is a {@code String} specifying the 2283 * simple name of the desired field. 2284 * 2285 * <p> The field to be reflected is determined by the algorithm that 2286 * follows. Let C be the class or interface represented by this {@code Class} object: 2287 * 2288 * <OL> 2289 * <LI> If C declares a public field with the name specified, that is the 2290 * field to be reflected.</LI> 2291 * <LI> If no field was found in step 1 above, this algorithm is applied 2292 * recursively to each direct superinterface of C. The direct 2293 * superinterfaces are searched in the order they were declared.</LI> 2294 * <LI> If no field was found in steps 1 and 2 above, and C has a 2295 * superclass S, then this algorithm is invoked recursively upon S. 2296 * If C has no superclass, then a {@code NoSuchFieldException} 2297 * is thrown.</LI> 2298 * </OL> 2299 * 2300 * <p> If this {@code Class} object represents an array type, then this 2301 * method does not find the {@code length} field of the array type. 2302 * 2303 * @param name the field name 2304 * @return the {@code Field} object of this class specified by 2305 * {@code name} 2306 * @throws NoSuchFieldException if a field with the specified name is 2307 * not found. 2308 * @throws NullPointerException if {@code name} is {@code null} 2309 * @throws SecurityException 2310 * If a security manager, <i>s</i>, is present and 2311 * the caller's class loader is not the same as or an 2312 * ancestor of the class loader for the current class and 2313 * invocation of {@link SecurityManager#checkPackageAccess 2314 * s.checkPackageAccess()} denies access to the package 2315 * of this class. 2316 * 2317 * @since 1.1 2318 * @jls 8.2 Class Members 2319 * @jls 8.3 Field Declarations 2320 */ 2321 // Android-changed: Removed SecurityException. 2322 @CallerSensitive getField(String name)2323 public Field getField(String name) throws NoSuchFieldException { 2324 Objects.requireNonNull(name); 2325 Field result = getPublicFieldRecursive(name); 2326 if (result == null) { 2327 throw new NoSuchFieldException(name); 2328 } 2329 return result; 2330 } 2331 2332 /** 2333 * The native implementation of the {@code getField} method. 2334 * 2335 * @throws NullPointerException 2336 * if name is null. 2337 * @see #getField(String) 2338 */ 2339 @FastNative getPublicFieldRecursive(String name)2340 private native Field getPublicFieldRecursive(String name); 2341 2342 /** 2343 * Returns a {@code Method} object that reflects the specified public 2344 * member method of the class or interface represented by this 2345 * {@code Class} object. The {@code name} parameter is a 2346 * {@code String} specifying the simple name of the desired method. The 2347 * {@code parameterTypes} parameter is an array of {@code Class} 2348 * objects that identify the method's formal parameter types, in declared 2349 * order. If {@code parameterTypes} is {@code null}, it is 2350 * treated as if it were an empty array. 2351 * 2352 * <p> If this {@code Class} object represents an array type, then this 2353 * method finds any public method inherited by the array type from 2354 * {@code Object} except method {@code clone()}. 2355 * 2356 * <p> If this {@code Class} object represents an interface then this 2357 * method does not find any implicitly declared method from 2358 * {@code Object}. Therefore, if no methods are explicitly declared in 2359 * this interface or any of its superinterfaces, then this method does not 2360 * find any method. 2361 * 2362 * <p> This method does not find any method with name "{@code <init>}" or 2363 * "{@code <clinit>}". 2364 * 2365 * <p> Generally, the method to be reflected is determined by the 4 step 2366 * algorithm that follows. 2367 * Let C be the class or interface represented by this {@code Class} object: 2368 * <ol> 2369 * <li> A union of methods is composed of: 2370 * <ol type="a"> 2371 * <li> C's declared public instance and static methods as returned by 2372 * {@link #getDeclaredMethods()} and filtered to include only public 2373 * methods that match given {@code name} and {@code parameterTypes}</li> 2374 * <li> If C is a class other than {@code Object}, then include the result 2375 * of invoking this algorithm recursively on the superclass of C.</li> 2376 * <li> Include the results of invoking this algorithm recursively on all 2377 * direct superinterfaces of C, but include only instance methods.</li> 2378 * </ol></li> 2379 * <li> This union is partitioned into subsets of methods with same 2380 * return type (the selection of methods from step 1 also guarantees that 2381 * they have the same method name and parameter types).</li> 2382 * <li> Within each such subset only the most specific methods are selected. 2383 * Let method M be a method from a set of methods with same VM 2384 * signature (return type, name, parameter types). 2385 * M is most specific if there is no such method N != M from the same 2386 * set, such that N is more specific than M. N is more specific than M 2387 * if: 2388 * <ol type="a"> 2389 * <li> N is declared by a class and M is declared by an interface; or</li> 2390 * <li> N and M are both declared by classes or both by interfaces and 2391 * N's declaring type is the same as or a subtype of M's declaring type 2392 * (clearly, if M's and N's declaring types are the same type, then 2393 * M and N are the same method).</li> 2394 * </ol></li> 2395 * <li> The result of this algorithm is chosen arbitrarily from the methods 2396 * with most specific return type among all selected methods from step 3. 2397 * Let R be a return type of a method M from the set of all selected methods 2398 * from step 3. M is a method with most specific return type if there is 2399 * no such method N != M from the same set, having return type S != R, 2400 * such that S is a subtype of R as determined by 2401 * R.class.{@link #isAssignableFrom}(S.class). 2402 * </ol> 2403 * 2404 * @apiNote There may be more than one method with matching name and 2405 * parameter types in a class because while the Java language forbids a 2406 * class to declare multiple methods with the same signature but different 2407 * return types, the Java virtual machine does not. This 2408 * increased flexibility in the virtual machine can be used to 2409 * implement various language features. For example, covariant 2410 * returns can be implemented with {@linkplain 2411 * java.lang.reflect.Method#isBridge bridge methods}; the bridge 2412 * method and the overriding method would have the same 2413 * signature but different return types. This method would return the 2414 * overriding method as it would have a more specific return type. 2415 * 2416 * @param name the name of the method 2417 * @param parameterTypes the list of parameters 2418 * @return the {@code Method} object that matches the specified 2419 * {@code name} and {@code parameterTypes} 2420 * @throws NoSuchMethodException if a matching method is not found 2421 * or if the name is "<init>"or "<clinit>". 2422 * @throws NullPointerException if {@code name} is {@code null} 2423 * @throws SecurityException 2424 * If a security manager, <i>s</i>, is present and 2425 * the caller's class loader is not the same as or an 2426 * ancestor of the class loader for the current class and 2427 * invocation of {@link SecurityManager#checkPackageAccess 2428 * s.checkPackageAccess()} denies access to the package 2429 * of this class. 2430 * 2431 * @jls 8.2 Class Members 2432 * @jls 8.4 Method Declarations 2433 * @since 1.1 2434 */ 2435 @CallerSensitive getMethod(String name, Class<?>... parameterTypes)2436 public Method getMethod(String name, Class<?>... parameterTypes) 2437 throws NoSuchMethodException, SecurityException { 2438 Objects.requireNonNull(name); 2439 // Android-changed: Removed SecurityManager check. 2440 return getMethod(name, parameterTypes, true); 2441 } 2442 2443 2444 /** 2445 * Returns a {@code Constructor} object that reflects the specified 2446 * public constructor of the class represented by this {@code Class} 2447 * object. The {@code parameterTypes} parameter is an array of 2448 * {@code Class} objects that identify the constructor's formal 2449 * parameter types, in declared order. 2450 * 2451 * If this {@code Class} object represents an inner class 2452 * declared in a non-static context, the formal parameter types 2453 * include the explicit enclosing instance as the first parameter. 2454 * 2455 * <p> The constructor to reflect is the public constructor of the class 2456 * represented by this {@code Class} object whose formal parameter 2457 * types match those specified by {@code parameterTypes}. 2458 * 2459 * @param parameterTypes the parameter array 2460 * @return the {@code Constructor} object of the public constructor that 2461 * matches the specified {@code parameterTypes} 2462 * @throws NoSuchMethodException if a matching method is not found. 2463 * @throws SecurityException 2464 * If a security manager, <i>s</i>, is present and 2465 * the caller's class loader is not the same as or an 2466 * ancestor of the class loader for the current class and 2467 * invocation of {@link SecurityManager#checkPackageAccess 2468 * s.checkPackageAccess()} denies access to the package 2469 * of this class. 2470 * 2471 * @since 1.1 2472 */ getConstructor(Class<?>.... parameterTypes)2473 public Constructor<T> getConstructor(Class<?>... parameterTypes) 2474 throws NoSuchMethodException, SecurityException 2475 { 2476 // Android-changed: Removed SecurityManager check. 2477 return getConstructor0(parameterTypes, Member.PUBLIC); 2478 } 2479 2480 2481 /** 2482 * Returns an array of {@code Class} objects reflecting all the 2483 * classes and interfaces declared as members of the class represented by 2484 * this {@code Class} object. This includes public, protected, default 2485 * (package) access, and private classes and interfaces declared by the 2486 * class, but excludes inherited classes and interfaces. This method 2487 * returns an array of length 0 if the class declares no classes or 2488 * interfaces as members, or if this {@code Class} object represents a 2489 * primitive type, an array class, or void. 2490 * 2491 * @return the array of {@code Class} objects representing all the 2492 * declared members of this class 2493 * @throws SecurityException 2494 * If a security manager, <i>s</i>, is present and any of the 2495 * following conditions is met: 2496 * 2497 * <ul> 2498 * 2499 * <li> the caller's class loader is not the same as the 2500 * class loader of this class and invocation of 2501 * {@link SecurityManager#checkPermission 2502 * s.checkPermission} method with 2503 * {@code RuntimePermission("accessDeclaredMembers")} 2504 * denies access to the declared classes within this class 2505 * 2506 * <li> the caller's class loader is not the same as or an 2507 * ancestor of the class loader for the current class and 2508 * invocation of {@link SecurityManager#checkPackageAccess 2509 * s.checkPackageAccess()} denies access to the package 2510 * of this class 2511 * 2512 * </ul> 2513 * 2514 * @since 1.1 2515 * @jls 8.5 Member Type Declarations 2516 */ 2517 // Android-changed: Removed SecurityException. 2518 /* 2519 @CallerSensitive 2520 public Class<?>[] getDeclaredClasses() throws SecurityException { 2521 @SuppressWarnings("removal") 2522 SecurityManager sm = System.getSecurityManager(); 2523 if (sm != null) { 2524 checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), false); 2525 } 2526 return getDeclaredClasses0(); 2527 } 2528 */ 2529 @FastNative getDeclaredClasses()2530 public native Class<?>[] getDeclaredClasses(); 2531 2532 /** 2533 * Returns an array of {@code Field} objects reflecting all the fields 2534 * declared by the class or interface represented by this 2535 * {@code Class} object. This includes public, protected, default 2536 * (package) access, and private fields, but excludes inherited fields. 2537 * 2538 * <p> If this {@code Class} object represents a class or interface with no 2539 * declared fields, then this method returns an array of length 0. 2540 * 2541 * <p> If this {@code Class} object represents an array type, a primitive 2542 * type, or void, then this method returns an array of length 0. 2543 * 2544 * <p> The elements in the returned array are not sorted and are not in any 2545 * particular order. 2546 * 2547 * @return the array of {@code Field} objects representing all the 2548 * declared fields of this class 2549 * @throws SecurityException 2550 * If a security manager, <i>s</i>, is present and any of the 2551 * following conditions is met: 2552 * 2553 * <ul> 2554 * 2555 * <li> the caller's class loader is not the same as the 2556 * class loader of this class and invocation of 2557 * {@link SecurityManager#checkPermission 2558 * s.checkPermission} method with 2559 * {@code RuntimePermission("accessDeclaredMembers")} 2560 * denies access to the declared fields within this class 2561 * 2562 * <li> the caller's class loader is not the same as or an 2563 * ancestor of the class loader for the current class and 2564 * invocation of {@link SecurityManager#checkPackageAccess 2565 * s.checkPackageAccess()} denies access to the package 2566 * of this class 2567 * 2568 * </ul> 2569 * 2570 * @since 1.1 2571 * @jls 8.2 Class Members 2572 * @jls 8.3 Field Declarations 2573 */ 2574 // Android-changed: Removed SecurityException. 2575 /* 2576 @CallerSensitive 2577 public Field[] getDeclaredFields() throws SecurityException { 2578 @SuppressWarnings("removal") 2579 SecurityManager sm = System.getSecurityManager(); 2580 if (sm != null) { 2581 checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true); 2582 } 2583 return copyFields(privateGetDeclaredFields(false)); 2584 } 2585 */ 2586 @FastNative getDeclaredFields()2587 public native Field[] getDeclaredFields(); 2588 2589 /** 2590 * Returns an array of {@code RecordComponent} objects representing all the 2591 * record components of this record class, or {@code null} if this class is 2592 * not a record class. 2593 * 2594 * <p> The components are returned in the same order that they are declared 2595 * in the record header. The array is empty if this record class has no 2596 * components. If the class is not a record class, that is {@link 2597 * #isRecord()} returns {@code false}, then this method returns {@code null}. 2598 * Conversely, if {@link #isRecord()} returns {@code true}, then this method 2599 * returns a non-null value. 2600 * 2601 * @apiNote 2602 * <p> The following method can be used to find the record canonical constructor: 2603 * 2604 * <pre>{@code 2605 * static <T extends Record> Constructor<T> getCanonicalConstructor(Class<T> cls) 2606 * throws NoSuchMethodException { 2607 * Class<?>[] paramTypes = 2608 * Arrays.stream(cls.getRecordComponents()) 2609 * .map(RecordComponent::getType) 2610 * .toArray(Class<?>[]::new); 2611 * return cls.getDeclaredConstructor(paramTypes); 2612 * }}</pre> 2613 * 2614 * @return An array of {@code RecordComponent} objects representing all the 2615 * record components of this record class, or {@code null} if this 2616 * class is not a record class 2617 * @throws SecurityException 2618 * If a security manager, <i>s</i>, is present and any of the 2619 * following conditions is met: 2620 * 2621 * <ul> 2622 * 2623 * <li> the caller's class loader is not the same as the 2624 * class loader of this class and invocation of 2625 * {@link SecurityManager#checkPermission 2626 * s.checkPermission} method with 2627 * {@code RuntimePermission("accessDeclaredMembers")} 2628 * denies access to the declared methods within this class 2629 * 2630 * <li> the caller's class loader is not the same as or an 2631 * ancestor of the class loader for the current class and 2632 * invocation of {@link SecurityManager#checkPackageAccess 2633 * s.checkPackageAccess()} denies access to the package 2634 * of this class 2635 * 2636 * </ul> 2637 * 2638 * @jls 8.10 Record Classes 2639 * @since 16 2640 */ 2641 @CallerSensitive getRecordComponents()2642 public RecordComponent[] getRecordComponents() { 2643 // Android-removed: Android doesn't support SecurityManager. 2644 /* 2645 @SuppressWarnings("removal") 2646 SecurityManager sm = System.getSecurityManager(); 2647 if (sm != null) { 2648 checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true); 2649 } 2650 */ 2651 if (!isRecord()) { 2652 return null; 2653 } 2654 return getRecordComponents0(); 2655 } 2656 2657 /** 2658 * Populates a list of fields without performing any security or type 2659 * resolution checks first. If no fields exist, the list is not modified. 2660 * 2661 * @param publicOnly Whether to return only public fields. 2662 * @hide 2663 */ 2664 @FastNative getDeclaredFieldsUnchecked(boolean publicOnly)2665 public native Field[] getDeclaredFieldsUnchecked(boolean publicOnly); 2666 2667 /** 2668 * Returns an array containing {@code Method} objects reflecting all the 2669 * declared methods of the class or interface represented by this {@code 2670 * Class} object, including public, protected, default (package) 2671 * access, and private methods, but excluding inherited methods. 2672 * The declared methods may include methods <em>not</em> in the 2673 * source of the class or interface, including {@linkplain 2674 * Method#isBridge bridge methods} and other {@linkplain 2675 * Executable#isSynthetic synthetic} methods added by compilers. 2676 * 2677 * <p> If this {@code Class} object represents a class or interface that 2678 * has multiple declared methods with the same name and parameter types, 2679 * but different return types, then the returned array has a {@code Method} 2680 * object for each such method. 2681 * 2682 * <p> If this {@code Class} object represents a class or interface that 2683 * has a class initialization method {@code <clinit>}, then the returned 2684 * array does <em>not</em> have a corresponding {@code Method} object. 2685 * 2686 * <p> If this {@code Class} object represents a class or interface with no 2687 * declared methods, then the returned array has length 0. 2688 * 2689 * <p> If this {@code Class} object represents an array type, a primitive 2690 * type, or void, then the returned array has length 0. 2691 * 2692 * <p> The elements in the returned array are not sorted and are not in any 2693 * particular order. 2694 * 2695 * @return the array of {@code Method} objects representing all the 2696 * declared methods of this class 2697 * @throws SecurityException 2698 * If a security manager, <i>s</i>, is present and any of the 2699 * following conditions is met: 2700 * 2701 * <ul> 2702 * 2703 * <li> the caller's class loader is not the same as the 2704 * class loader of this class and invocation of 2705 * {@link SecurityManager#checkPermission 2706 * s.checkPermission} method with 2707 * {@code RuntimePermission("accessDeclaredMembers")} 2708 * denies access to the declared methods within this class 2709 * 2710 * <li> the caller's class loader is not the same as or an 2711 * ancestor of the class loader for the current class and 2712 * invocation of {@link SecurityManager#checkPackageAccess 2713 * s.checkPackageAccess()} denies access to the package 2714 * of this class 2715 * 2716 * </ul> 2717 * 2718 * @jls 8.2 Class Members 2719 * @jls 8.4 Method Declarations 2720 * @see <a 2721 * href="{@docRoot}/java.base/java/lang/reflect/package-summary.html#LanguageJvmModel">Java 2722 * programming language and JVM modeling in core reflection</a> 2723 * @since 1.1 2724 */ getDeclaredMethods()2725 public Method[] getDeclaredMethods() throws SecurityException { 2726 // Android-changed: Removed SecurityManager check. 2727 Method[] result = getDeclaredMethodsUnchecked(false); 2728 for (Method m : result) { 2729 // Throw NoClassDefFoundError if types cannot be resolved. 2730 m.getReturnType(); 2731 m.getParameterTypes(); 2732 } 2733 return result; 2734 } 2735 2736 /** 2737 * Populates a list of methods without performing any security or type 2738 * resolution checks first. If no methods exist, the list is not modified. 2739 * 2740 * @param publicOnly Whether to return only public methods. 2741 * @hide 2742 */ 2743 @FastNative getDeclaredMethodsUnchecked(boolean publicOnly)2744 public native Method[] getDeclaredMethodsUnchecked(boolean publicOnly); 2745 2746 /** 2747 * Returns an array of {@code Constructor} objects reflecting all the 2748 * constructors declared by the class represented by this 2749 * {@code Class} object. These are public, protected, default 2750 * (package) access, and private constructors. The elements in the array 2751 * returned are not sorted and are not in any particular order. If the 2752 * class has a default constructor, it is included in the returned array. 2753 * This method returns an array of length 0 if this {@code Class} 2754 * object represents an interface, a primitive type, an array class, or 2755 * void. 2756 * 2757 * <p> See <cite>The Java Language Specification</cite>, 2758 * section {@jls 8.2}. 2759 * 2760 * @return the array of {@code Constructor} objects representing all the 2761 * declared constructors of this class 2762 * @throws SecurityException 2763 * If a security manager, <i>s</i>, is present and any of the 2764 * following conditions is met: 2765 * 2766 * <ul> 2767 * 2768 * <li> the caller's class loader is not the same as the 2769 * class loader of this class and invocation of 2770 * {@link SecurityManager#checkPermission 2771 * s.checkPermission} method with 2772 * {@code RuntimePermission("accessDeclaredMembers")} 2773 * denies access to the declared constructors within this class 2774 * 2775 * <li> the caller's class loader is not the same as or an 2776 * ancestor of the class loader for the current class and 2777 * invocation of {@link SecurityManager#checkPackageAccess 2778 * s.checkPackageAccess()} denies access to the package 2779 * of this class 2780 * 2781 * </ul> 2782 * 2783 * @since 1.1 2784 * @jls 8.8 Constructor Declarations 2785 */ getDeclaredConstructors()2786 public Constructor<?>[] getDeclaredConstructors() throws SecurityException { 2787 // Android-changed: Removed SecurityManager check. 2788 return getDeclaredConstructorsInternal(false); 2789 } 2790 2791 2792 /** 2793 * Returns the constructor with the given parameters if it is defined by this class; 2794 * {@code null} otherwise. This may return a non-public member. 2795 */ 2796 @FastNative getDeclaredConstructorsInternal(boolean publicOnly)2797 private native Constructor<?>[] getDeclaredConstructorsInternal(boolean publicOnly); 2798 2799 /** 2800 * Returns a {@code Field} object that reflects the specified declared 2801 * field of the class or interface represented by this {@code Class} 2802 * object. The {@code name} parameter is a {@code String} that specifies 2803 * the simple name of the desired field. 2804 * 2805 * <p> If this {@code Class} object represents an array type, then this 2806 * method does not find the {@code length} field of the array type. 2807 * 2808 * @param name the name of the field 2809 * @return the {@code Field} object for the specified field in this 2810 * class 2811 * @throws NoSuchFieldException if a field with the specified name is 2812 * not found. 2813 * @throws NullPointerException if {@code name} is {@code null} 2814 * @throws SecurityException 2815 * If a security manager, <i>s</i>, is present and any of the 2816 * following conditions is met: 2817 * 2818 * <ul> 2819 * 2820 * <li> the caller's class loader is not the same as the 2821 * class loader of this class and invocation of 2822 * {@link SecurityManager#checkPermission 2823 * s.checkPermission} method with 2824 * {@code RuntimePermission("accessDeclaredMembers")} 2825 * denies access to the declared field 2826 * 2827 * <li> the caller's class loader is not the same as or an 2828 * ancestor of the class loader for the current class and 2829 * invocation of {@link SecurityManager#checkPackageAccess 2830 * s.checkPackageAccess()} denies access to the package 2831 * of this class 2832 * 2833 * </ul> 2834 * 2835 * @since 1.1 2836 * @jls 8.2 Class Members 2837 * @jls 8.3 Field Declarations 2838 */ 2839 // Android-changed: ART has a different JNI layer. 2840 // Android-changed: Removed SecurityException. 2841 /* 2842 @CallerSensitive 2843 public Field getDeclaredField(String name) 2844 throws NoSuchFieldException, SecurityException { 2845 Objects.requireNonNull(name); 2846 @SuppressWarnings("removal") 2847 SecurityManager sm = System.getSecurityManager(); 2848 if (sm != null) { 2849 checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true); 2850 } 2851 Field field = searchFields(privateGetDeclaredFields(false), name); 2852 if (field == null) { 2853 throw new NoSuchFieldException(name); 2854 } 2855 return getReflectionFactory().copyField(field); 2856 } 2857 */ 2858 @FastNative getDeclaredField(String name)2859 public native Field getDeclaredField(String name) throws NoSuchFieldException; 2860 2861 /** 2862 * Returns the subset of getDeclaredFields which are public. 2863 */ 2864 @FastNative getPublicDeclaredFields()2865 private native Field[] getPublicDeclaredFields(); 2866 2867 /** 2868 * Returns a {@code Method} object that reflects the specified 2869 * declared method of the class or interface represented by this 2870 * {@code Class} object. The {@code name} parameter is a 2871 * {@code String} that specifies the simple name of the desired 2872 * method, and the {@code parameterTypes} parameter is an array of 2873 * {@code Class} objects that identify the method's formal parameter 2874 * types, in declared order. If more than one method with the same 2875 * parameter types is declared in a class, and one of these methods has a 2876 * return type that is more specific than any of the others, that method is 2877 * returned; otherwise one of the methods is chosen arbitrarily. If the 2878 * name is "<init>"or "<clinit>" a {@code NoSuchMethodException} 2879 * is raised. 2880 * 2881 * <p> If this {@code Class} object represents an array type, then this 2882 * method does not find the {@code clone()} method. 2883 * 2884 * @param name the name of the method 2885 * @param parameterTypes the parameter array 2886 * @return the {@code Method} object for the method of this class 2887 * matching the specified name and parameters 2888 * @throws NoSuchMethodException if a matching method is not found. 2889 * @throws NullPointerException if {@code name} is {@code null} 2890 * @throws SecurityException 2891 * If a security manager, <i>s</i>, is present and any of the 2892 * following conditions is met: 2893 * 2894 * <ul> 2895 * 2896 * <li> the caller's class loader is not the same as the 2897 * class loader of this class and invocation of 2898 * {@link SecurityManager#checkPermission 2899 * s.checkPermission} method with 2900 * {@code RuntimePermission("accessDeclaredMembers")} 2901 * denies access to the declared method 2902 * 2903 * <li> the caller's class loader is not the same as or an 2904 * ancestor of the class loader for the current class and 2905 * invocation of {@link SecurityManager#checkPackageAccess 2906 * s.checkPackageAccess()} denies access to the package 2907 * of this class 2908 * 2909 * </ul> 2910 * 2911 * @jls 8.2 Class Members 2912 * @jls 8.4 Method Declarations 2913 * @since 1.1 2914 */ 2915 @CallerSensitive getDeclaredMethod(String name, Class<?>... parameterTypes)2916 public Method getDeclaredMethod(String name, Class<?>... parameterTypes) 2917 throws NoSuchMethodException, SecurityException { 2918 // Android-changed: ART has a different JNI layer. 2919 return getMethod(name, parameterTypes, false); 2920 } 2921 2922 // BEGIN Android-added: Internal methods to implement getMethod(...). getMethod(String name, Class<?>[] parameterTypes, boolean recursivePublicMethods)2923 private Method getMethod(String name, Class<?>[] parameterTypes, boolean recursivePublicMethods) 2924 throws NoSuchMethodException { 2925 Objects.requireNonNull(name); 2926 if (parameterTypes == null) { 2927 parameterTypes = EmptyArray.CLASS; 2928 } 2929 for (Class<?> c : parameterTypes) { 2930 if (c == null) { 2931 throw new NoSuchMethodException("parameter type is null"); 2932 } 2933 } 2934 Method result = recursivePublicMethods ? getPublicMethodRecursive(name, parameterTypes) 2935 : getDeclaredMethodInternal(name, parameterTypes); 2936 // Fail if we didn't find the method or it was expected to be public. 2937 if (result == null || 2938 (recursivePublicMethods && !Modifier.isPublic(result.getAccessFlags()))) { 2939 throw new NoSuchMethodException(getName() + "." + name + " " 2940 + Arrays.toString(parameterTypes)); 2941 } 2942 return result; 2943 } getPublicMethodRecursive(String name, Class<?>[] parameterTypes)2944 private Method getPublicMethodRecursive(String name, Class<?>[] parameterTypes) { 2945 // search superclasses 2946 for (Class<?> c = this; c != null; c = c.getSuperclass()) { 2947 Method result = c.getDeclaredMethodInternal(name, parameterTypes); 2948 if (result != null && Modifier.isPublic(result.getAccessFlags())) { 2949 return result; 2950 } 2951 } 2952 2953 return findInterfaceMethod(name, parameterTypes); 2954 } 2955 2956 /** 2957 * Returns an instance method that's defined on this class or any super classes, regardless 2958 * of its access flags. Constructors are excluded. 2959 * 2960 * This function does not perform access checks and its semantics don't match any dex byte code 2961 * instruction or public reflection API. This is used by {@code MethodHandles.findVirtual} 2962 * which will perform access checks on the returned method. 2963 * 2964 * @hide 2965 */ getInstanceMethod(String name, Class<?>[] parameterTypes)2966 public Method getInstanceMethod(String name, Class<?>[] parameterTypes) 2967 throws NoSuchMethodException, IllegalAccessException { 2968 for (Class<?> c = this; c != null; c = c.getSuperclass()) { 2969 Method result = c.getDeclaredMethodInternal(name, parameterTypes); 2970 if (result != null && !Modifier.isStatic(result.getModifiers())) { 2971 return result; 2972 } 2973 } 2974 2975 return findInterfaceMethod(name, parameterTypes); 2976 } 2977 findInterfaceMethod(String name, Class<?>[] parameterTypes)2978 private Method findInterfaceMethod(String name, Class<?>[] parameterTypes) { 2979 Object[] iftable = ifTable; 2980 if (iftable != null) { 2981 // Search backwards so more specific interfaces are searched first. This ensures that 2982 // the method we return is not overridden by one of it's subtypes that this class also 2983 // implements. 2984 for (int i = iftable.length - 2; i >= 0; i -= 2) { 2985 Class<?> ifc = (Class<?>) iftable[i]; 2986 Method result = ifc.getPublicMethodRecursive(name, parameterTypes); 2987 if (result != null && Modifier.isPublic(result.getAccessFlags())) { 2988 return result; 2989 } 2990 } 2991 } 2992 2993 return null; 2994 } 2995 // END Android-added: Internal methods to implement getMethod(...). 2996 2997 // Android-removed: unused method. 2998 /* 2999 * Returns the list of {@code Method} objects for the declared public 3000 * methods of this class or interface that have the specified method name 3001 * and parameter types. 3002 * 3003 * @param name the name of the method 3004 * @param parameterTypes the parameter array 3005 * @return the list of {@code Method} objects for the public methods of 3006 * this class matching the specified name and parameters 3007 * 3008 List<Method> getDeclaredPublicMethods(String name, Class<?>... parameterTypes) { 3009 Method[] methods = privateGetDeclaredMethods(/* publicOnly * true); 3010 ReflectionFactory factory = getReflectionFactory(); 3011 List<Method> result = new ArrayList<>(); 3012 for (Method method : methods) { 3013 if (method.getName().equals(name) 3014 && Arrays.equals( 3015 factory.getExecutableSharedParameterTypes(method), 3016 parameterTypes)) { 3017 result.add(factory.copyMethod(method)); 3018 } 3019 } 3020 return result; 3021 } 3022 */ 3023 3024 /** 3025 * Returns a {@code Constructor} object that reflects the specified 3026 * constructor of the class or interface represented by this 3027 * {@code Class} object. The {@code parameterTypes} parameter is 3028 * an array of {@code Class} objects that identify the constructor's 3029 * formal parameter types, in declared order. 3030 * 3031 * If this {@code Class} object represents an inner class 3032 * declared in a non-static context, the formal parameter types 3033 * include the explicit enclosing instance as the first parameter. 3034 * 3035 * @param parameterTypes the parameter array 3036 * @return The {@code Constructor} object for the constructor with the 3037 * specified parameter list 3038 * @throws NoSuchMethodException if a matching method is not found. 3039 * @throws SecurityException 3040 * If a security manager, <i>s</i>, is present and any of the 3041 * following conditions is met: 3042 * 3043 * <ul> 3044 * 3045 * <li> the caller's class loader is not the same as the 3046 * class loader of this class and invocation of 3047 * {@link SecurityManager#checkPermission 3048 * s.checkPermission} method with 3049 * {@code RuntimePermission("accessDeclaredMembers")} 3050 * denies access to the declared constructor 3051 * 3052 * <li> the caller's class loader is not the same as or an 3053 * ancestor of the class loader for the current class and 3054 * invocation of {@link SecurityManager#checkPackageAccess 3055 * s.checkPackageAccess()} denies access to the package 3056 * of this class 3057 * 3058 * </ul> 3059 * 3060 * @since 1.1 3061 */ 3062 @CallerSensitive getDeclaredConstructor(Class<?>.... parameterTypes)3063 public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes) 3064 throws NoSuchMethodException, SecurityException 3065 { 3066 // Android-changed: Removed SecurityManager check. 3067 return getConstructor0(parameterTypes, Member.DECLARED); 3068 } 3069 3070 // Android-changed: Removed javadoc related to Module. 3071 /** 3072 * Finds a resource with a given name. 3073 * 3074 * <p> The rules for 3075 * searching resources associated with a given class are implemented by the 3076 * defining {@linkplain ClassLoader class loader} of the class. This method 3077 * delegates to this {@code Class} object's class loader. 3078 * If this {@code Class} object was loaded by the bootstrap class loader, 3079 * the method delegates to {@link ClassLoader#getSystemResourceAsStream}. 3080 * 3081 * <p> Before delegation, an absolute resource name is constructed from the 3082 * given resource name using this algorithm: 3083 * 3084 * <ul> 3085 * 3086 * <li> If the {@code name} begins with a {@code '/'} 3087 * (<code>'\u002f'</code>), then the absolute name of the resource is the 3088 * portion of the {@code name} following the {@code '/'}. 3089 * 3090 * <li> Otherwise, the absolute name is of the following form: 3091 * 3092 * <blockquote> 3093 * {@code modified_package_name/name} 3094 * </blockquote> 3095 * 3096 * <p> Where the {@code modified_package_name} is the package name of this 3097 * object with {@code '/'} substituted for {@code '.'} 3098 * (<code>'\u002e'</code>). 3099 * 3100 * </ul> 3101 * 3102 * @param name name of the desired resource 3103 * @return A {@link java.io.InputStream} object; {@code null} if no 3104 * resource with this name is found. 3105 * @throws NullPointerException If {@code name} is {@code null} 3106 * @since 1.1 3107 * @revised 9 3108 */ 3109 @CallerSensitive getResourceAsStream(String name)3110 public InputStream getResourceAsStream(String name) { 3111 name = resolveName(name); 3112 // unnamed module 3113 // Android-changed: Removed BuiltinClassLoader, Module usage, and SecurityManager check. 3114 ClassLoader cl = getClassLoader(); 3115 if (cl == null) { 3116 return ClassLoader.getSystemResourceAsStream(name); 3117 } else { 3118 return cl.getResourceAsStream(name); 3119 } 3120 } 3121 3122 // Android-changed: Remove javadoc related to the module system. 3123 /** 3124 * Finds a resource with a given name. 3125 * 3126 * <p> The rules for 3127 * searching resources associated with a given class are implemented by the 3128 * defining {@linkplain ClassLoader class loader} of the class. This method 3129 * delegates to this {@code Class} object's class loader. 3130 * If this {@code Class} object was loaded by the bootstrap class loader, 3131 * the method delegates to {@link ClassLoader#getSystemResource}. 3132 * 3133 * <p> Before delegation, an absolute resource name is constructed from the 3134 * given resource name using this algorithm: 3135 * 3136 * <ul> 3137 * 3138 * <li> If the {@code name} begins with a {@code '/'} 3139 * (<code>'\u002f'</code>), then the absolute name of the resource is the 3140 * portion of the {@code name} following the {@code '/'}. 3141 * 3142 * <li> Otherwise, the absolute name is of the following form: 3143 * 3144 * <blockquote> 3145 * {@code modified_package_name/name} 3146 * </blockquote> 3147 * 3148 * <p> Where the {@code modified_package_name} is the package name of this 3149 * object with {@code '/'} substituted for {@code '.'} 3150 * (<code>'\u002e'</code>). 3151 * 3152 * </ul> 3153 * 3154 * @param name name of the desired resource 3155 * @return A {@link java.net.URL} object; {@code null} if no resource with 3156 * this name is found. 3157 * @throws NullPointerException If {@code name} is {@code null} 3158 * @since 1.1 3159 * @revised 9 3160 */ 3161 @CallerSensitive getResource(String name)3162 public URL getResource(String name) { 3163 name = resolveName(name); 3164 // unnamed module 3165 // Android-changed: Removed BuiltinClassLoader, Module usage, and SecurityManager check. 3166 ClassLoader cl = getClassLoader(); 3167 if (cl == null) { 3168 return ClassLoader.getSystemResource(name); 3169 } else { 3170 return cl.getResource(name); 3171 } 3172 } 3173 3174 // Android-removed: Remove unused method. 3175 /* 3176 * Returns true if a resource with the given name can be located by the 3177 * given caller. All resources in a module can be located by code in 3178 * the module. For other callers, then the package needs to be open to 3179 * the caller. 3180 * 3181 private boolean isOpenToCaller(String name, Class<?> caller) { 3182 // assert getModule().isNamed(); 3183 Module thisModule = getModule(); 3184 Module callerModule = (caller != null) ? caller.getModule() : null; 3185 if (callerModule != thisModule) { 3186 String pn = Resources.toPackageName(name); 3187 if (thisModule.getDescriptor().packages().contains(pn)) { 3188 if (callerModule == null && !thisModule.isOpen(pn)) { 3189 // no caller, package not open 3190 return false; 3191 } 3192 if (!thisModule.isOpen(pn, callerModule)) { 3193 // package not open to caller 3194 return false; 3195 } 3196 } 3197 } 3198 return true; 3199 } 3200 3201 3202 /** protection domain returned when the internal domain is null * 3203 private static java.security.ProtectionDomain allPermDomain; 3204 */ 3205 3206 /** 3207 * Returns the {@code ProtectionDomain} of this class. If there is a 3208 * security manager installed, this method first calls the security 3209 * manager's {@code checkPermission} method with a 3210 * {@code RuntimePermission("getProtectionDomain")} permission to 3211 * ensure it's ok to get the 3212 * {@code ProtectionDomain}. 3213 * 3214 * @return the ProtectionDomain of this class 3215 * 3216 * @throws SecurityException 3217 * if a security manager exists and its 3218 * {@code checkPermission} method doesn't allow 3219 * getting the ProtectionDomain. 3220 * 3221 * @see java.security.ProtectionDomain 3222 * @see SecurityManager#checkPermission 3223 * @see java.lang.RuntimePermission 3224 * @since 1.2 3225 */ getProtectionDomain()3226 public java.security.ProtectionDomain getProtectionDomain() { 3227 // Android-changed: Removed SecurityManager check. 3228 return null; 3229 } 3230 3231 // Android-removed: Removed SecurityManager check. 3232 /* 3233 // package-private 3234 java.security.ProtectionDomain protectionDomain() { 3235 java.security.ProtectionDomain pd = getProtectionDomain0(); 3236 if (pd == null) { 3237 if (allPermDomain == null) { 3238 java.security.Permissions perms = 3239 new java.security.Permissions(); 3240 perms.add(SecurityConstants.ALL_PERMISSION); 3241 allPermDomain = 3242 new java.security.ProtectionDomain(null, perms); 3243 } 3244 pd = allPermDomain; 3245 } 3246 return pd; 3247 } 3248 3249 /** 3250 * Returns the ProtectionDomain of this class. 3251 *//* 3252 private native java.security.ProtectionDomain getProtectionDomain0(); 3253 */ 3254 3255 /* 3256 * Return the runtime's Class object for the named 3257 * primitive type. 3258 */ 3259 @FastNative getPrimitiveClass(String name)3260 static native Class<?> getPrimitiveClass(String name); 3261 3262 // Android-removed: Remove unused method. 3263 /* 3264 * Check if client is allowed to access members. If access is denied, 3265 * throw a SecurityException. 3266 * 3267 * This method also enforces package access. 3268 * 3269 * <p> Default policy: allow all clients access with normal Java access 3270 * control. 3271 * 3272 * <p> NOTE: should only be called if a SecurityManager is installed 3273 * 3274 private void checkMemberAccess(@SuppressWarnings("removal") SecurityManager sm, int which, 3275 Class<?> caller, boolean checkProxyInterfaces) { 3276 *//* Default policy allows access to all {@link Member#PUBLIC} members, 3277 * as well as access to classes that have the same class loader as the caller. 3278 * In all other cases, it requires RuntimePermission("accessDeclaredMembers") 3279 * permission. 3280 *//* 3281 final ClassLoader ccl = ClassLoader.getClassLoader(caller); 3282 if (which != Member.PUBLIC) { 3283 final ClassLoader cl = getClassLoader0(); 3284 if (ccl != cl) { 3285 sm.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION); 3286 } 3287 } 3288 this.checkPackageAccess(sm, ccl, checkProxyInterfaces); 3289 } 3290 3291 /* 3292 * Checks if a client loaded in ClassLoader ccl is allowed to access this 3293 * class under the current package access policy. If access is denied, 3294 * throw a SecurityException. 3295 * 3296 * NOTE: this method should only be called if a SecurityManager is active 3297 * 3298 private void checkPackageAccess(@SuppressWarnings("removal") SecurityManager sm, final ClassLoader ccl, 3299 boolean checkProxyInterfaces) { 3300 final ClassLoader cl = getClassLoader0(); 3301 3302 if (ReflectUtil.needsPackageAccessCheck(ccl, cl)) { 3303 String pkg = this.getPackageName(); 3304 if (!pkg.isEmpty()) { 3305 // skip the package access check on a proxy class in default proxy package 3306 if (!Proxy.isProxyClass(this) || ReflectUtil.isNonPublicProxyClass(this)) { 3307 sm.checkPackageAccess(pkg); 3308 } 3309 } 3310 } 3311 // check package access on the proxy interfaces 3312 if (checkProxyInterfaces && Proxy.isProxyClass(this)) { 3313 ReflectUtil.checkProxyPackageAccess(ccl, this.getInterfaces()); 3314 } 3315 } 3316 */ 3317 3318 /* 3319 * Checks if a client loaded in ClassLoader ccl is allowed to access the provided 3320 * classes under the current package access policy. If access is denied, 3321 * throw a SecurityException. 3322 * 3323 * NOTE: this method should only be called if a SecurityManager is active 3324 * classes must be non-empty 3325 * all classes provided must be loaded by the same ClassLoader 3326 * NOTE: this method does not support Proxy classes 3327 *//* 3328 private static void checkPackageAccessForPermittedSubclasses(@SuppressWarnings("removal") SecurityManager sm, 3329 final ClassLoader ccl, Class<?>[] subClasses) { 3330 final ClassLoader cl = subClasses[0].getClassLoader0(); 3331 3332 if (ReflectUtil.needsPackageAccessCheck(ccl, cl)) { 3333 Set<String> packages = new HashSet<>(); 3334 3335 for (Class<?> c : subClasses) { 3336 if (Proxy.isProxyClass(c)) 3337 throw new InternalError("a permitted subclass should not be a proxy class: " + c); 3338 String pkg = c.getPackageName(); 3339 if (!pkg.isEmpty()) { 3340 packages.add(pkg); 3341 } 3342 } 3343 for (String pkg : packages) { 3344 sm.checkPackageAccess(pkg); 3345 } 3346 } 3347 } 3348 */ 3349 3350 /** 3351 * Add a package name prefix if the name is not absolute. Remove leading "/" 3352 * if name is absolute 3353 */ resolveName(String name)3354 private String resolveName(String name) { 3355 if (!name.startsWith("/")) { 3356 String baseName = getPackageName(); 3357 if (!baseName.isEmpty()) { 3358 int len = baseName.length() + 1 + name.length(); 3359 StringBuilder sb = new StringBuilder(len); 3360 name = sb.append(baseName.replace('.', '/')) 3361 .append('/') 3362 .append(name) 3363 .toString(); 3364 } 3365 } else { 3366 name = name.substring(1); 3367 } 3368 return name; 3369 } 3370 getConstructor0(Class<?>[] parameterTypes, int which)3371 private Constructor<T> getConstructor0(Class<?>[] parameterTypes, 3372 int which) throws NoSuchMethodException 3373 { 3374 if (parameterTypes == null) { 3375 parameterTypes = EmptyArray.CLASS; 3376 } 3377 for (Class<?> c : parameterTypes) { 3378 if (c == null) { 3379 throw new NoSuchMethodException("parameter type is null"); 3380 } 3381 } 3382 Constructor<T> result = getDeclaredConstructorInternal(parameterTypes); 3383 if (result == null || which == Member.PUBLIC && !Modifier.isPublic(result.getAccessFlags())) { 3384 throw new NoSuchMethodException(getName() + ".<init> " 3385 + Arrays.toString(parameterTypes)); 3386 } 3387 return result; 3388 } 3389 3390 /* 3391 /** 3392 * Atomic operations support. 3393 *//* 3394 private static class Atomic { 3395 // initialize Unsafe machinery here, since we need to call Class.class instance method 3396 // and have to avoid calling it in the static initializer of the Class class... 3397 private static final Unsafe unsafe = Unsafe.getUnsafe(); 3398 // offset of Class.reflectionData instance field 3399 private static final long reflectionDataOffset 3400 = unsafe.objectFieldOffset(Class.class, "reflectionData"); 3401 // offset of Class.annotationType instance field 3402 private static final long annotationTypeOffset 3403 = unsafe.objectFieldOffset(Class.class, "annotationType"); 3404 // offset of Class.annotationData instance field 3405 private static final long annotationDataOffset 3406 = unsafe.objectFieldOffset(Class.class, "annotationData"); 3407 3408 static <T> boolean casReflectionData(Class<?> clazz, 3409 SoftReference<ReflectionData<T>> oldData, 3410 SoftReference<ReflectionData<T>> newData) { 3411 return unsafe.compareAndSetReference(clazz, reflectionDataOffset, oldData, newData); 3412 } 3413 3414 static boolean casAnnotationType(Class<?> clazz, 3415 AnnotationType oldType, 3416 AnnotationType newType) { 3417 return unsafe.compareAndSetReference(clazz, annotationTypeOffset, oldType, newType); 3418 } 3419 3420 static boolean casAnnotationData(Class<?> clazz, 3421 AnnotationData oldData, 3422 AnnotationData newData) { 3423 return unsafe.compareAndSetReference(clazz, annotationDataOffset, oldData, newData); 3424 } 3425 } 3426 3427 *//** 3428 * Reflection support. 3429 *//* 3430 3431 // Reflection data caches various derived names and reflective members. Cached 3432 // values may be invalidated when JVM TI RedefineClasses() is called 3433 private static class ReflectionData<T> { 3434 volatile Field[] declaredFields; 3435 volatile Field[] publicFields; 3436 volatile Method[] declaredMethods; 3437 volatile Method[] publicMethods; 3438 volatile Constructor<T>[] declaredConstructors; 3439 volatile Constructor<T>[] publicConstructors; 3440 // Intermediate results for getFields and getMethods 3441 volatile Field[] declaredPublicFields; 3442 volatile Method[] declaredPublicMethods; 3443 volatile Class<?>[] interfaces; 3444 3445 // Cached names 3446 String simpleName; 3447 String canonicalName; 3448 static final String NULL_SENTINEL = new String(); 3449 3450 // Value of classRedefinedCount when we created this ReflectionData instance 3451 final int redefinedCount; 3452 3453 ReflectionData(int redefinedCount) { 3454 this.redefinedCount = redefinedCount; 3455 } 3456 } 3457 3458 private transient volatile SoftReference<ReflectionData<T>> reflectionData; 3459 3460 // Incremented by the VM on each call to JVM TI RedefineClasses() 3461 // that redefines this class or a superclass. 3462 private transient volatile int classRedefinedCount; 3463 3464 // Lazily create and cache ReflectionData 3465 private ReflectionData<T> reflectionData() { 3466 SoftReference<ReflectionData<T>> reflectionData = this.reflectionData; 3467 int classRedefinedCount = this.classRedefinedCount; 3468 ReflectionData<T> rd; 3469 if (reflectionData != null && 3470 (rd = reflectionData.get()) != null && 3471 rd.redefinedCount == classRedefinedCount) { 3472 return rd; 3473 } 3474 // else no SoftReference or cleared SoftReference or stale ReflectionData 3475 // -> create and replace new instance 3476 return newReflectionData(reflectionData, classRedefinedCount); 3477 } 3478 3479 private ReflectionData<T> newReflectionData(SoftReference<ReflectionData<T>> oldReflectionData, 3480 int classRedefinedCount) { 3481 while (true) { 3482 ReflectionData<T> rd = new ReflectionData<>(classRedefinedCount); 3483 // try to CAS it... 3484 if (Atomic.casReflectionData(this, oldReflectionData, new SoftReference<>(rd))) { 3485 return rd; 3486 } 3487 // else retry 3488 oldReflectionData = this.reflectionData; 3489 classRedefinedCount = this.classRedefinedCount; 3490 if (oldReflectionData != null && 3491 (rd = oldReflectionData.get()) != null && 3492 rd.redefinedCount == classRedefinedCount) { 3493 return rd; 3494 } 3495 } 3496 } 3497 3498 // Generic signature handling 3499 private native String getGenericSignature0(); 3500 3501 // Generic info repository; lazily initialized 3502 private transient volatile ClassRepository genericInfo; 3503 3504 // accessor for factory 3505 private GenericsFactory getFactory() { 3506 // create scope and factory 3507 return CoreReflectionFactory.make(this, ClassScope.make(this)); 3508 } 3509 3510 // accessor for generic info repository; 3511 // generic info is lazily initialized 3512 private ClassRepository getGenericInfo() { 3513 ClassRepository genericInfo = this.genericInfo; 3514 if (genericInfo == null) { 3515 String signature = getGenericSignature0(); 3516 if (signature == null) { 3517 genericInfo = ClassRepository.NONE; 3518 } else { 3519 genericInfo = ClassRepository.make(signature, getFactory()); 3520 } 3521 this.genericInfo = genericInfo; 3522 } 3523 return (genericInfo != ClassRepository.NONE) ? genericInfo : null; 3524 } 3525 3526 // Annotations handling 3527 native byte[] getRawAnnotations(); 3528 // Since 1.8 3529 native byte[] getRawTypeAnnotations(); 3530 static byte[] getExecutableTypeAnnotationBytes(Executable ex) { 3531 return getReflectionFactory().getExecutableTypeAnnotationBytes(ex); 3532 } 3533 3534 native ConstantPool getConstantPool(); 3535 3536 // 3537 // 3538 // java.lang.reflect.Field handling 3539 // 3540 // 3541 3542 // Returns an array of "root" fields. These Field objects must NOT 3543 // be propagated to the outside world, but must instead be copied 3544 // via ReflectionFactory.copyField. 3545 private Field[] privateGetDeclaredFields(boolean publicOnly) { 3546 Field[] res; 3547 ReflectionData<T> rd = reflectionData(); 3548 if (rd != null) { 3549 res = publicOnly ? rd.declaredPublicFields : rd.declaredFields; 3550 if (res != null) return res; 3551 } 3552 // No cached value available; request value from VM 3553 res = Reflection.filterFields(this, getDeclaredFields0(publicOnly)); 3554 if (rd != null) { 3555 if (publicOnly) { 3556 rd.declaredPublicFields = res; 3557 } else { 3558 rd.declaredFields = res; 3559 } 3560 } 3561 return res; 3562 } 3563 3564 // Returns an array of "root" fields. These Field objects must NOT 3565 // be propagated to the outside world, but must instead be copied 3566 // via ReflectionFactory.copyField. 3567 private Field[] privateGetPublicFields() { 3568 Field[] res; 3569 ReflectionData<T> rd = reflectionData(); 3570 if (rd != null) { 3571 res = rd.publicFields; 3572 if (res != null) return res; 3573 } 3574 3575 // Use a linked hash set to ensure order is preserved and 3576 // fields from common super interfaces are not duplicated 3577 LinkedHashSet<Field> fields = new LinkedHashSet<>(); 3578 3579 // Local fields 3580 addAll(fields, privateGetDeclaredFields(true)); 3581 3582 // Direct superinterfaces, recursively 3583 for (Class<?> si : getInterfaces()) { 3584 addAll(fields, si.privateGetPublicFields()); 3585 } 3586 3587 // Direct superclass, recursively 3588 Class<?> sc = getSuperclass(); 3589 if (sc != null) { 3590 addAll(fields, sc.privateGetPublicFields()); 3591 } 3592 3593 res = fields.toArray(new Field[0]); 3594 if (rd != null) { 3595 rd.publicFields = res; 3596 } 3597 return res; 3598 } 3599 3600 private static void addAll(Collection<Field> c, Field[] o) { 3601 for (Field f : o) { 3602 c.add(f); 3603 } 3604 } 3605 3606 3607 // 3608 // 3609 // java.lang.reflect.Constructor handling 3610 // 3611 // 3612 3613 // Returns an array of "root" constructors. These Constructor 3614 // objects must NOT be propagated to the outside world, but must 3615 // instead be copied via ReflectionFactory.copyConstructor. 3616 private Constructor<T>[] privateGetDeclaredConstructors(boolean publicOnly) { 3617 Constructor<T>[] res; 3618 ReflectionData<T> rd = reflectionData(); 3619 if (rd != null) { 3620 res = publicOnly ? rd.publicConstructors : rd.declaredConstructors; 3621 if (res != null) return res; 3622 } 3623 // No cached value available; request value from VM 3624 if (isInterface()) { 3625 @SuppressWarnings("unchecked") 3626 Constructor<T>[] temporaryRes = (Constructor<T>[]) new Constructor<?>[0]; 3627 res = temporaryRes; 3628 } else { 3629 res = getDeclaredConstructors0(publicOnly); 3630 } 3631 if (rd != null) { 3632 if (publicOnly) { 3633 rd.publicConstructors = res; 3634 } else { 3635 rd.declaredConstructors = res; 3636 } 3637 } 3638 return res; 3639 } 3640 3641 // 3642 // 3643 // java.lang.reflect.Method handling 3644 // 3645 // 3646 3647 // Returns an array of "root" methods. These Method objects must NOT 3648 // be propagated to the outside world, but must instead be copied 3649 // via ReflectionFactory.copyMethod. 3650 private Method[] privateGetDeclaredMethods(boolean publicOnly) { 3651 Method[] res; 3652 ReflectionData<T> rd = reflectionData(); 3653 if (rd != null) { 3654 res = publicOnly ? rd.declaredPublicMethods : rd.declaredMethods; 3655 if (res != null) return res; 3656 } 3657 // No cached value available; request value from VM 3658 res = Reflection.filterMethods(this, getDeclaredMethods0(publicOnly)); 3659 if (rd != null) { 3660 if (publicOnly) { 3661 rd.declaredPublicMethods = res; 3662 } else { 3663 rd.declaredMethods = res; 3664 } 3665 } 3666 return res; 3667 } 3668 3669 // Returns an array of "root" methods. These Method objects must NOT 3670 // be propagated to the outside world, but must instead be copied 3671 // via ReflectionFactory.copyMethod. 3672 private Method[] privateGetPublicMethods() { 3673 Method[] res; 3674 ReflectionData<T> rd = reflectionData(); 3675 if (rd != null) { 3676 res = rd.publicMethods; 3677 if (res != null) return res; 3678 } 3679 3680 // No cached value available; compute value recursively. 3681 // Start by fetching public declared methods... 3682 PublicMethods pms = new PublicMethods(); 3683 for (Method m : privateGetDeclaredMethods(*//* publicOnly *//* true)) { 3684 pms.merge(m); 3685 } 3686 // ...then recur over superclass methods... 3687 Class<?> sc = getSuperclass(); 3688 if (sc != null) { 3689 for (Method m : sc.privateGetPublicMethods()) { 3690 pms.merge(m); 3691 } 3692 } 3693 // ...and finally over direct superinterfaces. 3694 for (Class<?> intf : getInterfaces(*//* cloneArray *//* false)) { 3695 for (Method m : intf.privateGetPublicMethods()) { 3696 // static interface methods are not inherited 3697 if (!Modifier.isStatic(m.getModifiers())) { 3698 pms.merge(m); 3699 } 3700 } 3701 } 3702 3703 res = pms.toArray(); 3704 if (rd != null) { 3705 rd.publicMethods = res; 3706 } 3707 return res; 3708 } 3709 3710 3711 // 3712 // Helpers for fetchers of one field, method, or constructor 3713 // 3714 3715 // This method does not copy the returned Field object! 3716 private static Field searchFields(Field[] fields, String name) { 3717 for (Field field : fields) { 3718 if (field.getName().equals(name)) { 3719 return field; 3720 } 3721 } 3722 return null; 3723 } 3724 3725 // Returns a "root" Field object. This Field object must NOT 3726 // be propagated to the outside world, but must instead be copied 3727 // via ReflectionFactory.copyField. 3728 private Field getField0(String name) { 3729 // Note: the intent is that the search algorithm this routine 3730 // uses be equivalent to the ordering imposed by 3731 // privateGetPublicFields(). It fetches only the declared 3732 // public fields for each class, however, to reduce the number 3733 // of Field objects which have to be created for the common 3734 // case where the field being requested is declared in the 3735 // class which is being queried. 3736 Field res; 3737 // Search declared public fields 3738 if ((res = searchFields(privateGetDeclaredFields(true), name)) != null) { 3739 return res; 3740 } 3741 // Direct superinterfaces, recursively 3742 Class<?>[] interfaces = getInterfaces(*//* cloneArray *//* false); 3743 for (Class<?> c : interfaces) { 3744 if ((res = c.getField0(name)) != null) { 3745 return res; 3746 } 3747 } 3748 // Direct superclass, recursively 3749 if (!isInterface()) { 3750 Class<?> c = getSuperclass(); 3751 if (c != null) { 3752 if ((res = c.getField0(name)) != null) { 3753 return res; 3754 } 3755 } 3756 } 3757 return null; 3758 } 3759 3760 // This method does not copy the returned Method object! 3761 private static Method searchMethods(Method[] methods, 3762 String name, 3763 Class<?>[] parameterTypes) 3764 { 3765 ReflectionFactory fact = getReflectionFactory(); 3766 Method res = null; 3767 for (Method m : methods) { 3768 if (m.getName().equals(name) 3769 && arrayContentsEq(parameterTypes, 3770 fact.getExecutableSharedParameterTypes(m)) 3771 && (res == null 3772 || (res.getReturnType() != m.getReturnType() 3773 && res.getReturnType().isAssignableFrom(m.getReturnType())))) 3774 res = m; 3775 } 3776 return res; 3777 } 3778 3779 private static final Class<?>[] EMPTY_CLASS_ARRAY = new Class<?>[0]; 3780 3781 // Returns a "root" Method object. This Method object must NOT 3782 // be propagated to the outside world, but must instead be copied 3783 // via ReflectionFactory.copyMethod. 3784 private Method getMethod0(String name, Class<?>[] parameterTypes) { 3785 PublicMethods.MethodList res = getMethodsRecursive( 3786 name, 3787 parameterTypes == null ? EMPTY_CLASS_ARRAY : parameterTypes, 3788 *//* includeStatic *//* true); 3789 return res == null ? null : res.getMostSpecific(); 3790 } 3791 3792 // Returns a list of "root" Method objects. These Method objects must NOT 3793 // be propagated to the outside world, but must instead be copied 3794 // via ReflectionFactory.copyMethod. 3795 private PublicMethods.MethodList getMethodsRecursive(String name, 3796 Class<?>[] parameterTypes, 3797 boolean includeStatic) { 3798 // 1st check declared public methods 3799 Method[] methods = privateGetDeclaredMethods(*//* publicOnly *//* true); 3800 PublicMethods.MethodList res = PublicMethods.MethodList 3801 .filter(methods, name, parameterTypes, includeStatic); 3802 // if there is at least one match among declared methods, we need not 3803 // search any further as such match surely overrides matching methods 3804 // declared in superclass(es) or interface(s). 3805 if (res != null) { 3806 return res; 3807 } 3808 3809 // if there was no match among declared methods, 3810 // we must consult the superclass (if any) recursively... 3811 Class<?> sc = getSuperclass(); 3812 if (sc != null) { 3813 res = sc.getMethodsRecursive(name, parameterTypes, includeStatic); 3814 } 3815 3816 // ...and coalesce the superclass methods with methods obtained 3817 // from directly implemented interfaces excluding static methods... 3818 for (Class<?> intf : getInterfaces(*//* cloneArray *//* false)) { 3819 res = PublicMethods.MethodList.merge( 3820 res, intf.getMethodsRecursive(name, parameterTypes, 3821 *//* includeStatic *//* false)); 3822 } 3823 3824 return res; 3825 } 3826 3827 // Returns a "root" Constructor object. This Constructor object must NOT 3828 // be propagated to the outside world, but must instead be copied 3829 // via ReflectionFactory.copyConstructor. 3830 private Constructor<T> getConstructor0(Class<?>[] parameterTypes, 3831 int which) throws NoSuchMethodException 3832 { 3833 ReflectionFactory fact = getReflectionFactory(); 3834 Constructor<T>[] constructors = privateGetDeclaredConstructors((which == Member.PUBLIC)); 3835 for (Constructor<T> constructor : constructors) { 3836 if (arrayContentsEq(parameterTypes, 3837 fact.getExecutableSharedParameterTypes(constructor))) { 3838 return constructor; 3839 } 3840 } 3841 throw new NoSuchMethodException(methodToString("<init>", parameterTypes)); 3842 } 3843 3844 // 3845 // Other helpers and base implementation 3846 // 3847 3848 private static boolean arrayContentsEq(Object[] a1, Object[] a2) { 3849 if (a1 == null) { 3850 return a2 == null || a2.length == 0; 3851 } 3852 3853 if (a2 == null) { 3854 return a1.length == 0; 3855 } 3856 3857 if (a1.length != a2.length) { 3858 return false; 3859 } 3860 3861 for (int i = 0; i < a1.length; i++) { 3862 if (a1[i] != a2[i]) { 3863 return false; 3864 } 3865 } 3866 3867 return true; 3868 } 3869 3870 private static Field[] copyFields(Field[] arg) { 3871 Field[] out = new Field[arg.length]; 3872 ReflectionFactory fact = getReflectionFactory(); 3873 for (int i = 0; i < arg.length; i++) { 3874 out[i] = fact.copyField(arg[i]); 3875 } 3876 return out; 3877 } 3878 3879 private static Method[] copyMethods(Method[] arg) { 3880 Method[] out = new Method[arg.length]; 3881 ReflectionFactory fact = getReflectionFactory(); 3882 for (int i = 0; i < arg.length; i++) { 3883 out[i] = fact.copyMethod(arg[i]); 3884 } 3885 return out; 3886 } 3887 3888 private static <U> Constructor<U>[] copyConstructors(Constructor<U>[] arg) { 3889 Constructor<U>[] out = arg.clone(); 3890 ReflectionFactory fact = getReflectionFactory(); 3891 for (int i = 0; i < out.length; i++) { 3892 out[i] = fact.copyConstructor(out[i]); 3893 } 3894 return out; 3895 } 3896 3897 private native Field[] getDeclaredFields0(boolean publicOnly); 3898 private native Method[] getDeclaredMethods0(boolean publicOnly); 3899 private native Constructor<T>[] getDeclaredConstructors0(boolean publicOnly); 3900 private native Class<?>[] getDeclaredClasses0(); 3901 3902 */ 3903 3904 /* 3905 * Returns an array containing the components of the Record attribute, 3906 * or null if the attribute is not present. 3907 * 3908 * Note that this method returns non-null array on a class with 3909 * the Record attribute even if this class is not a record. 3910 */ 3911 // BEGIN Android-changed: Re-implement getRecordComponents0() on ART. 3912 // private native RecordComponent[] getRecordComponents0(); getRecordComponents0()3913 private RecordComponent[] getRecordComponents0() { 3914 RecordComponents libcoreComponents = new RecordComponents(this); 3915 3916 // Every component should have a type and a name. 3917 String[] names = libcoreComponents.getNames(); 3918 Class<?>[] types = libcoreComponents.getTypes(); 3919 if (names == null || types == null) { 3920 // Return non-null array as per getRecordComponent() javadoc if isRecord() 3921 // returns true. 3922 return new RecordComponent[0]; 3923 } 3924 3925 // class_linker.cc should verify that names and types have the same length, or otherwise, 3926 // the class isn't loaded. 3927 int size = Math.min(names.length, types.length); 3928 RecordComponent[] components = new RecordComponent[size]; 3929 for (int i = 0; i < size; i++) { 3930 String name = names[i]; 3931 Class<?> type = types[i]; 3932 components[i] = new RecordComponent(this, name, type, libcoreComponents, i); 3933 } 3934 return components; 3935 } 3936 3937 /** 3938 * Used by {@link libcore.reflect.RecordComponents} 3939 * 3940 * @hide 3941 */ 3942 @FastNative getRecordAnnotationElement(String elementName, Class<T2[]> arrayClass)3943 public native <T2> T2[] getRecordAnnotationElement(String elementName, Class<T2[]> arrayClass); 3944 // END Android-changed: Re-implement getRecordComponents0() on ART. 3945 3946 @FastNative isRecord0()3947 private native boolean isRecord0(); 3948 3949 /** 3950 * Helper method to get the method name from arguments. 3951 *//* 3952 private String methodToString(String name, Class<?>[] argTypes) { 3953 return getName() + '.' + name + 3954 ((argTypes == null || argTypes.length == 0) ? 3955 "()" : 3956 Arrays.stream(argTypes) 3957 .map(c -> c == null ? "null" : c.getName()) 3958 .collect(Collectors.joining(",", "(", ")"))); 3959 } 3960 */ 3961 3962 /** use serialVersionUID from JDK 1.1 for interoperability */ 3963 @java.io.Serial 3964 private static final long serialVersionUID = 3206093459760846163L; 3965 3966 3967 /** 3968 * Returns the constructor with the given parameters if it is defined by this class; 3969 * {@code null} otherwise. This may return a non-public member. 3970 * 3971 * @param args the types of the parameters to the constructor. 3972 */ 3973 @FastNative getDeclaredConstructorInternal(Class<?>[] args)3974 private native Constructor<T> getDeclaredConstructorInternal(Class<?>[] args); 3975 3976 /** 3977 * Returns the assertion status that would be assigned to this 3978 * class if it were to be initialized at the time this method is invoked. 3979 * If this class has had its assertion status set, the most recent 3980 * setting will be returned; otherwise, if any package default assertion 3981 * status pertains to this class, the most recent setting for the most 3982 * specific pertinent package default assertion status is returned; 3983 * otherwise, if this class is not a system class (i.e., it has a 3984 * class loader) its class loader's default assertion status is returned; 3985 * otherwise, the system class default assertion status is returned. 3986 * 3987 * @apiNote 3988 * Few programmers will have any need for this method; it is provided 3989 * for the benefit of the JDK itself. (It allows a class to determine at 3990 * the time that it is initialized whether assertions should be enabled.) 3991 * Note that this method is not guaranteed to return the actual 3992 * assertion status that was (or will be) associated with the specified 3993 * class when it was (or will be) initialized. 3994 * 3995 * Android-note: AssertionStatuses are unsupported. This method will always return false. 3996 * 3997 * @return the desired assertion status of the specified class. 3998 * @see java.lang.ClassLoader#setClassAssertionStatus 3999 * @see java.lang.ClassLoader#setPackageAssertionStatus 4000 * @see java.lang.ClassLoader#setDefaultAssertionStatus 4001 * @since 1.4 4002 */ desiredAssertionStatus()4003 public boolean desiredAssertionStatus() { 4004 // Android-changaed: AssertionStatuses are unsupported. 4005 return false; 4006 } 4007 4008 /** 4009 * Returns the simple name of a member or local class, or {@code null} otherwise. 4010 */ 4011 @FastNative getSimpleNameNative()4012 private native String getSimpleNameNative(); 4013 4014 @FastNative getInnerClassFlags(int defaultValue)4015 private native int getInnerClassFlags(int defaultValue); 4016 4017 /** 4018 * Returns true if and only if this class was declared as an enum in the 4019 * source code. 4020 * 4021 * Note that {@link java.lang.Enum} is not itself an enum class. 4022 * 4023 * Also note that if an enum constant is declared with a class body, 4024 * the class of that enum constant object is an anonymous class 4025 * and <em>not</em> the class of the declaring enum class. The 4026 * {@link Enum#getDeclaringClass} method of an enum constant can 4027 * be used to get the class of the enum class declaring the 4028 * constant. 4029 * 4030 * @return true if and only if this class was declared as an enum in the 4031 * source code 4032 * @since 1.5 4033 * @jls 8.9.1 Enum Constants 4034 */ isEnum()4035 public boolean isEnum() { 4036 // An enum must both directly extend java.lang.Enum and have 4037 // the ENUM bit set; classes for specialized enum constants 4038 // don't do the former. 4039 return (this.getModifiers() & ENUM) != 0 && 4040 this.getSuperclass() == java.lang.Enum.class; 4041 } 4042 4043 /** 4044 * Returns {@code true} if and only if this class is a record class. 4045 * 4046 * <p> The {@linkplain #getSuperclass() direct superclass} of a record 4047 * class is {@code java.lang.Record}. A record class is {@linkplain 4048 * Modifier#FINAL final}. A record class has (possibly zero) record 4049 * components; {@link #getRecordComponents()} returns a non-null but 4050 * possibly empty value for a record. 4051 * 4052 * <p> Note that class {@link Record} is not a record class and thus 4053 * invoking this method on class {@code Record} returns {@code false}. 4054 * 4055 * @return true if and only if this class is a record class, otherwise false 4056 * @jls 8.10 Record Classes 4057 * @since 16 4058 */ isRecord()4059 public boolean isRecord() { 4060 // this superclass and final modifier check is not strictly necessary 4061 // they are intrinsified and serve as a fast-path check 4062 return getSuperclass() == java.lang.Record.class && 4063 (this.getModifiers() & Modifier.FINAL) != 0 && 4064 isRecord0(); 4065 } 4066 4067 // Android-remvoed: Remove unsupported ReflectionFactory. 4068 /* 4069 // Fetches the factory for reflective objects 4070 @SuppressWarnings("removal") 4071 private static ReflectionFactory getReflectionFactory() { 4072 if (reflectionFactory == null) { 4073 reflectionFactory = 4074 java.security.AccessController.doPrivileged 4075 (new ReflectionFactory.GetReflectionFactoryAction()); 4076 } 4077 return reflectionFactory; 4078 } 4079 private static ReflectionFactory reflectionFactory; 4080 */ 4081 4082 /** 4083 * Returns the elements of this enum class or null if this 4084 * Class object does not represent an enum class. 4085 * 4086 * @return an array containing the values comprising the enum class 4087 * represented by this {@code Class} object in the order they're 4088 * declared, or null if this {@code Class} object does not 4089 * represent an enum class 4090 * @since 1.5 4091 * @jls 8.9.1 Enum Constants 4092 */ getEnumConstants()4093 public T[] getEnumConstants() { 4094 T[] values = getEnumConstantsShared(); 4095 return (values != null) ? values.clone() : null; 4096 } 4097 4098 // Android-changed: Made public/hidden instead of using sun.misc.SharedSecrets. 4099 /** 4100 * Returns the elements of this enum class or null if this 4101 * Class object does not represent an enum class; 4102 * identical to getEnumConstants except that the result is 4103 * uncloned, cached, and shared by all callers. 4104 * @hide 4105 */ getEnumConstantsShared()4106 public T[] getEnumConstantsShared() { 4107 if (!isEnum()) return null; 4108 return (T[]) Enum.getSharedConstants((Class) this); 4109 } 4110 4111 /* 4112 @SuppressWarnings("removal") 4113 T[] getEnumConstantsShared() { 4114 T[] constants = enumConstants; 4115 if (constants == null) { 4116 if (!isEnum()) return null; 4117 try { 4118 final Method values = getMethod("values"); 4119 java.security.AccessController.doPrivileged( 4120 new java.security.PrivilegedAction<>() { 4121 public Void run() { 4122 values.setAccessible(true); 4123 return null; 4124 } 4125 }); 4126 @SuppressWarnings("unchecked") 4127 T[] temporaryConstants = (T[])values.invoke(null); 4128 enumConstants = constants = temporaryConstants; 4129 } 4130 // These can happen when users concoct enum-like classes 4131 // that don't comply with the enum spec. 4132 catch (InvocationTargetException | NoSuchMethodException | 4133 IllegalAccessException ex) { return null; } 4134 } 4135 return constants; 4136 } 4137 private transient volatile T[] enumConstants; 4138 */ 4139 4140 // Android-removed: Remove unused method. 4141 /* 4142 *//** 4143 * Returns a map from simple name to enum constant. This package-private 4144 * method is used internally by Enum to implement 4145 * {@code public static <T extends Enum<T>> T valueOf(Class<T>, String)} 4146 * efficiently. Note that the map is returned by this method is 4147 * created lazily on first use. Typically it won't ever get created. 4148 *//* 4149 Map<String, T> enumConstantDirectory() { 4150 Map<String, T> directory = enumConstantDirectory; 4151 if (directory == null) { 4152 T[] universe = getEnumConstantsShared(); 4153 if (universe == null) 4154 throw new IllegalArgumentException( 4155 getName() + " is not an enum class"); 4156 directory = new HashMap<>((int)(universe.length / 0.75f) + 1); 4157 for (T constant : universe) { 4158 directory.put(((Enum<?>)constant).name(), constant); 4159 } 4160 enumConstantDirectory = directory; 4161 } 4162 return directory; 4163 } 4164 private transient volatile Map<String, T> enumConstantDirectory; 4165 */ 4166 4167 /** 4168 * Casts an object to the class or interface represented 4169 * by this {@code Class} object. 4170 * 4171 * @param obj the object to be cast 4172 * @return the object after casting, or null if obj is null 4173 * 4174 * @throws ClassCastException if the object is not 4175 * null and is not assignable to the type T. 4176 * 4177 * @since 1.5 4178 */ 4179 @SuppressWarnings("unchecked") 4180 @IntrinsicCandidate cast(Object obj)4181 public T cast(Object obj) { 4182 if (obj != null && !isInstance(obj)) 4183 throw new ClassCastException(cannotCastMsg(obj)); 4184 return (T) obj; 4185 } 4186 cannotCastMsg(Object obj)4187 private String cannotCastMsg(Object obj) { 4188 return "Cannot cast " + obj.getClass().getName() + " to " + getName(); 4189 } 4190 4191 /** 4192 * Casts this {@code Class} object to represent a subclass of the class 4193 * represented by the specified class object. Checks that the cast 4194 * is valid, and throws a {@code ClassCastException} if it is not. If 4195 * this method succeeds, it always returns a reference to this {@code Class} object. 4196 * 4197 * <p>This method is useful when a client needs to "narrow" the type of 4198 * a {@code Class} object to pass it to an API that restricts the 4199 * {@code Class} objects that it is willing to accept. A cast would 4200 * generate a compile-time warning, as the correctness of the cast 4201 * could not be checked at runtime (because generic types are implemented 4202 * by erasure). 4203 * 4204 * @param <U> the type to cast this {@code Class} object to 4205 * @param clazz the class of the type to cast this {@code Class} object to 4206 * @return this {@code Class} object, cast to represent a subclass of 4207 * the specified class object. 4208 * @throws ClassCastException if this {@code Class} object does not 4209 * represent a subclass of the specified class (here "subclass" includes 4210 * the class itself). 4211 * @since 1.5 4212 */ 4213 @SuppressWarnings("unchecked") asSubclass(Class<U> clazz)4214 public <U> Class<? extends U> asSubclass(Class<U> clazz) { 4215 if (clazz.isAssignableFrom(this)) 4216 return (Class<? extends U>) this; 4217 else 4218 throw new ClassCastException(this.toString() + 4219 " cannot be cast to " + clazz.getName()); 4220 } 4221 4222 /** 4223 * {@inheritDoc} 4224 * <p>Note that any annotation returned by this method is a 4225 * declaration annotation. 4226 * 4227 * @throws NullPointerException {@inheritDoc} 4228 * @since 1.5 4229 */ 4230 @Override 4231 @SuppressWarnings("unchecked") getAnnotation(Class<A> annotationClass)4232 public <A extends Annotation> A getAnnotation(Class<A> annotationClass) { 4233 Objects.requireNonNull(annotationClass); 4234 4235 A annotation = getDeclaredAnnotation(annotationClass); 4236 if (annotation != null) { 4237 return annotation; 4238 } 4239 4240 if (annotationClass.isDeclaredAnnotationPresent(Inherited.class)) { 4241 for (Class<?> sup = getSuperclass(); sup != null; sup = sup.getSuperclass()) { 4242 annotation = sup.getDeclaredAnnotation(annotationClass); 4243 if (annotation != null) { 4244 return annotation; 4245 } 4246 } 4247 } 4248 4249 return null; 4250 } 4251 4252 /** 4253 * {@inheritDoc} 4254 * @throws NullPointerException {@inheritDoc} 4255 * @since 1.5 4256 */ 4257 @Override isAnnotationPresent(Class<? extends Annotation> annotationClass)4258 public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) { 4259 if (annotationClass == null) { 4260 throw new NullPointerException("annotationClass == null"); 4261 } 4262 4263 if (isDeclaredAnnotationPresent(annotationClass)) { 4264 return true; 4265 } 4266 4267 if (annotationClass.isDeclaredAnnotationPresent(Inherited.class)) { 4268 for (Class<?> sup = getSuperclass(); sup != null; sup = sup.getSuperclass()) { 4269 if (sup.isDeclaredAnnotationPresent(annotationClass)) { 4270 return true; 4271 } 4272 } 4273 } 4274 4275 return false; 4276 } 4277 4278 /** 4279 * {@inheritDoc} 4280 * <p>Note that any annotations returned by this method are 4281 * declaration annotations. 4282 * 4283 * @throws NullPointerException {@inheritDoc} 4284 * @since 1.8 4285 */ 4286 @Override getAnnotationsByType(Class<A> annotationClass)4287 public <A extends Annotation> A[] getAnnotationsByType(Class<A> annotationClass) { 4288 // Find any associated annotations [directly or repeatably (indirectly) present on this]. 4289 A[] annotations = GenericDeclaration.super.getAnnotationsByType(annotationClass); 4290 4291 if (annotations.length != 0) { 4292 return annotations; 4293 } 4294 4295 // Nothing was found, attempt looking for associated annotations recursively up to the root 4296 // class if and only if: 4297 // * The annotation class was marked with @Inherited. 4298 // 4299 // Inherited annotations are not coalesced into a single set: the first declaration found is 4300 // returned. 4301 4302 if (annotationClass.isDeclaredAnnotationPresent(Inherited.class)) { 4303 Class<?> superClass = getSuperclass(); // Returns null if klass's base is Object. 4304 if (superClass != null) { 4305 return superClass.getAnnotationsByType(annotationClass); 4306 } 4307 } 4308 4309 // Annotated was not marked with @Inherited, or no superclass. 4310 return (A[]) Array.newInstance(annotationClass, 0); // Safe by construction. 4311 } 4312 4313 /** 4314 * {@inheritDoc} 4315 * <p>Note that any annotations returned by this method are 4316 * declaration annotations. 4317 * 4318 * @throws NullPointerException {@inheritDoc} 4319 * @since 1.8 4320 */ 4321 @Override getDeclaredAnnotationsByType(Class<A> annotationClass)4322 public <A extends Annotation> A[] getDeclaredAnnotationsByType(Class<A> annotationClass) { 4323 Objects.requireNonNull(annotationClass); 4324 4325 // Android-changed: Altered method implementation for getDeclaredAnnotationsByType(Class). 4326 // return AnnotationSupport.getDirectlyAndIndirectlyPresent(annotationData().declaredAnnotations, 4327 // annotationClass); 4328 return GenericDeclaration.super.getDeclaredAnnotationsByType(annotationClass); 4329 } 4330 4331 /** 4332 * {@inheritDoc} 4333 * <p>Note that any annotations returned by this method are 4334 * declaration annotations. 4335 * 4336 * @since 1.5 4337 */ 4338 @Override getAnnotations()4339 public Annotation[] getAnnotations() { 4340 // Android-changed: ART reads annotations from dex files. 4341 // return AnnotationParser.toArray(annotationData().annotations); 4342 /* 4343 * We need to get the annotations declared on this class, plus the 4344 * annotations from superclasses that have the "@Inherited" annotation 4345 * set. We create a temporary map to use while we accumulate the 4346 * annotations and convert it to an array at the end. 4347 * 4348 * It's possible to have duplicates when annotations are inherited. 4349 * We use a Map to filter those out. 4350 * 4351 * HashMap might be overkill here. 4352 */ 4353 HashMap<Class<?>, Annotation> map = new HashMap<Class<?>, Annotation>(); 4354 for (Annotation declaredAnnotation : getDeclaredAnnotations()) { 4355 map.put(declaredAnnotation.annotationType(), declaredAnnotation); 4356 } 4357 for (Class<?> sup = getSuperclass(); sup != null; sup = sup.getSuperclass()) { 4358 for (Annotation declaredAnnotation : sup.getDeclaredAnnotations()) { 4359 Class<? extends Annotation> clazz = declaredAnnotation.annotationType(); 4360 if (!map.containsKey(clazz) && clazz.isDeclaredAnnotationPresent(Inherited.class)) { 4361 map.put(clazz, declaredAnnotation); 4362 } 4363 } 4364 } 4365 4366 /* Convert annotation values from HashMap to array. */ 4367 Collection<Annotation> coll = map.values(); 4368 return coll.toArray(new Annotation[coll.size()]); 4369 } 4370 4371 /** 4372 * {@inheritDoc} 4373 * <p>Note that any annotation returned by this method is a 4374 * declaration annotation. 4375 * 4376 * @throws NullPointerException {@inheritDoc} 4377 * @since 1.5 4378 */ 4379 // Android-changed: Re-implement on top of ART. 4380 /* 4381 @SuppressWarnings("unchecked") 4382 public <A extends Annotation> A getDeclaredAnnotation(Class<A> annotationClass) { 4383 Objects.requireNonNull(annotationClass); 4384 4385 return (A) annotationData().declaredAnnotations.get(annotationClass); 4386 } 4387 */ 4388 @Override 4389 @FastNative getDeclaredAnnotation(Class<A> annotationClass)4390 public native <A extends Annotation> A getDeclaredAnnotation(Class<A> annotationClass); 4391 4392 4393 /** 4394 * {@inheritDoc} 4395 * <p>Note that any annotations returned by this method are 4396 * declaration annotations. 4397 * 4398 * @since 1.5 4399 */ 4400 /* 4401 public Annotation[] getDeclaredAnnotations() { 4402 return AnnotationParser.toArray(annotationData().declaredAnnotations); 4403 } 4404 */ 4405 @Override 4406 @FastNative getDeclaredAnnotations()4407 public native Annotation[] getDeclaredAnnotations(); 4408 4409 // Android-removed: Remove unused fields and methods. 4410 /* 4411 // annotation data that might get invalidated when JVM TI RedefineClasses() is called 4412 private static class AnnotationData { 4413 final Map<Class<? extends Annotation>, Annotation> annotations; 4414 final Map<Class<? extends Annotation>, Annotation> declaredAnnotations; 4415 4416 // Value of classRedefinedCount when we created this AnnotationData instance 4417 final int redefinedCount; 4418 4419 AnnotationData(Map<Class<? extends Annotation>, Annotation> annotations, 4420 Map<Class<? extends Annotation>, Annotation> declaredAnnotations, 4421 int redefinedCount) { 4422 this.annotations = annotations; 4423 this.declaredAnnotations = declaredAnnotations; 4424 this.redefinedCount = redefinedCount; 4425 } 4426 } 4427 4428 // Annotation interfaces cache their internal (AnnotationType) form 4429 4430 @SuppressWarnings("UnusedDeclaration") 4431 private transient volatile AnnotationType annotationType; 4432 4433 boolean casAnnotationType(AnnotationType oldType, AnnotationType newType) { 4434 return Atomic.casAnnotationType(this, oldType, newType); 4435 } 4436 4437 AnnotationType getAnnotationType() { 4438 return annotationType; 4439 } 4440 4441 Map<Class<? extends Annotation>, Annotation> getDeclaredAnnotationMap() { 4442 return annotationData().declaredAnnotations; 4443 } 4444 4445 *//* Backing store of user-defined values pertaining to this class. 4446 * Maintained by the ClassValue class. 4447 *//* 4448 transient ClassValue.ClassValueMap classValueMap; 4449 */ 4450 4451 // Android-changed: ART doesn't support AnnotatedType. 4452 /* 4453 * Returns an {@code AnnotatedType} object that represents the use of a 4454 * type to specify the superclass of the entity represented by this {@code 4455 * Class} object. (The <em>use</em> of type Foo to specify the superclass 4456 * in '... extends Foo' is distinct from the <em>declaration</em> of class 4457 * Foo.) 4458 * 4459 * <p> If this {@code Class} object represents a class whose declaration 4460 * does not explicitly indicate an annotated superclass, then the return 4461 * value is an {@code AnnotatedType} object representing an element with no 4462 * annotations. 4463 * 4464 * <p> If this {@code Class} represents either the {@code Object} class, an 4465 * interface type, an array type, a primitive type, or void, the return 4466 * value is {@code null}. 4467 * 4468 * @return an object representing the superclass 4469 * @since 1.8 4470 *//* 4471 public AnnotatedType getAnnotatedSuperclass() { 4472 if (this == Object.class || 4473 isInterface() || 4474 isArray() || 4475 isPrimitive() || 4476 this == Void.TYPE) { 4477 return null; 4478 } 4479 4480 return TypeAnnotationParser.buildAnnotatedSuperclass(getRawTypeAnnotations(), getConstantPool(), this); 4481 } 4482 4483 * Returns an array of {@code AnnotatedType} objects that represent the use 4484 * of types to specify superinterfaces of the entity represented by this 4485 * {@code Class} object. (The <em>use</em> of type Foo to specify a 4486 * superinterface in '... implements Foo' is distinct from the 4487 * <em>declaration</em> of interface Foo.) 4488 * 4489 * <p> If this {@code Class} object represents a class, the return value is 4490 * an array containing objects representing the uses of interface types to 4491 * specify interfaces implemented by the class. The order of the objects in 4492 * the array corresponds to the order of the interface types used in the 4493 * 'implements' clause of the declaration of this {@code Class} object. 4494 * 4495 * <p> If this {@code Class} object represents an interface, the return 4496 * value is an array containing objects representing the uses of interface 4497 * types to specify interfaces directly extended by the interface. The 4498 * order of the objects in the array corresponds to the order of the 4499 * interface types used in the 'extends' clause of the declaration of this 4500 * {@code Class} object. 4501 * 4502 * <p> If this {@code Class} object represents a class or interface whose 4503 * declaration does not explicitly indicate any annotated superinterfaces, 4504 * the return value is an array of length 0. 4505 * 4506 * <p> If this {@code Class} object represents either the {@code Object} 4507 * class, an array type, a primitive type, or void, the return value is an 4508 * array of length 0. 4509 * 4510 * @return an array representing the superinterfaces 4511 * @since 1.8 4512 *//* 4513 public AnnotatedType[] getAnnotatedInterfaces() { 4514 return TypeAnnotationParser.buildAnnotatedInterfaces(getRawTypeAnnotations(), getConstantPool(), this); 4515 } 4516 */ 4517 4518 /** 4519 * Returns true if the annotation exists. 4520 */ 4521 @FastNative isDeclaredAnnotationPresent(Class<? extends Annotation> annotationClass)4522 private native boolean isDeclaredAnnotationPresent(Class<? extends Annotation> annotationClass); 4523 getSignatureAttribute()4524 private String getSignatureAttribute() { 4525 String[] annotation = getSignatureAnnotation(); 4526 if (annotation == null) { 4527 return null; 4528 } 4529 StringBuilder result = new StringBuilder(); 4530 for (String s : annotation) { 4531 result.append(s); 4532 } 4533 return result.toString(); 4534 } 4535 4536 @FastNative getSignatureAnnotation()4537 private native String[] getSignatureAnnotation(); 4538 4539 /** 4540 * Is this a runtime created proxy class? 4541 * 4542 * @hide 4543 */ isProxy()4544 public boolean isProxy() { 4545 return (accessFlags & 0x00040000) != 0; 4546 } 4547 4548 /** 4549 * @hide 4550 */ getAccessFlags()4551 public int getAccessFlags() { 4552 return accessFlags; 4553 } 4554 4555 /** 4556 * Returns the method if it is defined by this class; {@code null} otherwise. This may return a 4557 * non-public member. 4558 * 4559 * @param name the method name 4560 * @param args the method's parameter types 4561 */ 4562 @FastNative getDeclaredMethodInternal(String name, Class<?>[] args)4563 private native Method getDeclaredMethodInternal(String name, Class<?>[] args); 4564 4565 @FastNative ensureExtDataPresent()4566 native ClassExt ensureExtDataPresent(); 4567 4568 // Android-changed: Removed SecurityException. 4569 /** 4570 * Returns the nest host of the <a href=#nest>nest</a> to which the class 4571 * or interface represented by this {@code Class} object belongs. 4572 * Every class and interface belongs to exactly one nest. 4573 * 4574 * If the nest host of this class or interface has previously 4575 * been determined, then this method returns the nest host. 4576 * If the nest host of this class or interface has 4577 * not previously been determined, then this method determines the nest 4578 * host using the algorithm of JVMS 5.4.4, and returns it. 4579 * 4580 * Often, a class or interface belongs to a nest consisting only of itself, 4581 * in which case this method returns {@code this} to indicate that the class 4582 * or interface is the nest host. 4583 * 4584 * <p>If this {@code Class} object represents a primitive type, an array type, 4585 * or {@code void}, then this method returns {@code this}, 4586 * indicating that the represented entity belongs to the nest consisting only of 4587 * itself, and is the nest host. 4588 * 4589 * @return the nest host of this class or interface 4590 * @since 11 4591 * @jvms 4.7.28 The {@code NestHost} Attribute 4592 * @jvms 4.7.29 The {@code NestMembers} Attribute 4593 * @jvms 5.4.4 Access Control 4594 */ getNestHost()4595 public Class<?> getNestHost() { 4596 // Android-removed: Android has a different JNI layer. 4597 /* 4598 if (isPrimitive() || isArray()) { 4599 return this; 4600 } 4601 4602 Class<?> host = getNestHost0(); 4603 if (host == this) { 4604 return this; 4605 } 4606 // returning a different class requires a security check 4607 @SuppressWarnings("removal") 4608 SecurityManager sm = System.getSecurityManager(); 4609 if (sm != null) { 4610 checkPackageAccess(sm, 4611 ClassLoader.getClassLoader(Reflection.getCallerClass()), true); 4612 } 4613 return host; 4614 */ 4615 if (isPrimitive() || isArray() || Void.TYPE.equals(this)) { 4616 return this; 4617 } 4618 4619 Class host = getNestHostFromAnnotation(); 4620 if (host == null) { 4621 return this; 4622 } 4623 return (nestHostHasMember(host, this) ? host : this); 4624 } 4625 nestHostHasMember(Class<?> host, Class<?> member)4626 private static boolean nestHostHasMember(Class<?> host, Class<?> member) { 4627 if (host.equals(member)) { 4628 return true; 4629 } 4630 return nestMembersIncludeMember(host.getNestMembersFromAnnotation(), member); 4631 } 4632 nestMembersIncludeMember(Class<?>[] members, Class<?> member)4633 private static boolean nestMembersIncludeMember(Class<?>[] members, Class<?> member) { 4634 if (members == null) { 4635 return false; 4636 } 4637 for (Class m : members) { 4638 if (member.equals(m)) { 4639 return true; 4640 } 4641 } 4642 return false; 4643 } 4644 4645 @FastNative getNestHostFromAnnotation()4646 private native Class<?> getNestHostFromAnnotation(); 4647 4648 // Android-changed: This implementation comes from OpenJDK 17. 4649 /** 4650 * Determines if the given {@code Class} is a nestmate of the 4651 * class or interface represented by this {@code Class} object. 4652 * Two classes or interfaces are nestmates 4653 * if they have the same {@linkplain #getNestHost() nest host}. 4654 * 4655 * @param c the class to check 4656 * @return {@code true} if this class and {@code c} are members of 4657 * the same nest; and {@code false} otherwise. 4658 * 4659 * @since 11 4660 */ isNestmateOf(Class<?> c)4661 public boolean isNestmateOf(Class<?> c) { 4662 if (this == c) { 4663 return true; 4664 } 4665 if (isPrimitive() || isArray() || 4666 c.isPrimitive() || c.isArray()) { 4667 return false; 4668 } 4669 4670 return getNestHost() == c.getNestHost(); 4671 } 4672 4673 // Android-changed: Removed references to MethodHandles.Lookup#defineHiddenClass. 4674 /** 4675 * Returns an array containing {@code Class} objects representing all the 4676 * classes and interfaces that are members of the nest to which the class 4677 * or interface represented by this {@code Class} object belongs. 4678 * 4679 * First, this method obtains the {@linkplain #getNestHost() nest host}, 4680 * {@code H}, of the nest to which the class or interface represented by 4681 * this {@code Class} object belongs. The zeroth element of the returned 4682 * array is {@code H}. 4683 * 4684 * Then, for each class or interface {@code C} which is recorded by {@code H} 4685 * as being a member of its nest, this method attempts to obtain the {@code Class} 4686 * object for {@code C} (using {@linkplain #getClassLoader() the defining class 4687 * loader} of the current {@code Class} object), and then obtains the 4688 * {@linkplain #getNestHost() nest host} of the nest to which {@code C} belongs. 4689 * The classes and interfaces which are recorded by {@code H} as being members 4690 * of its nest, and for which {@code H} can be determined as their nest host, 4691 * are indicated by subsequent elements of the returned array. The order of 4692 * such elements is unspecified. Duplicates are permitted. 4693 * 4694 * <p>If this {@code Class} object represents a primitive type, an array type, 4695 * or {@code void}, then this method returns a single-element array containing 4696 * {@code this}. 4697 * 4698 * @apiNote 4699 * The returned array includes only the nest members recorded in the {@code NestMembers} 4700 * attribute. 4701 * 4702 * @return an array of all classes and interfaces in the same nest as 4703 * this class or interface 4704 * 4705 * @since 11 4706 * @see #getNestHost() 4707 * @jvms 4.7.28 The {@code NestHost} Attribute 4708 * @jvms 4.7.29 The {@code NestMembers} Attribute 4709 */ getNestMembers()4710 public Class<?>[] getNestMembers() { 4711 // Android-changed: ART has a different JNI layer. 4712 /* 4713 if (isPrimitive() || isArray()) { 4714 return new Class<?>[] { this }; 4715 } 4716 Class<?>[] members = getNestMembers0(); 4717 // Can't actually enable this due to bootstrapping issues 4718 // assert(members.length != 1 || members[0] == this); // expected invariant from VM 4719 4720 if (members.length > 1) { 4721 // If we return anything other than the current class we need 4722 // a security check 4723 @SuppressWarnings("removal") 4724 SecurityManager sm = System.getSecurityManager(); 4725 if (sm != null) { 4726 checkPackageAccess(sm, 4727 ClassLoader.getClassLoader(Reflection.getCallerClass()), true); 4728 } 4729 } 4730 return members; 4731 */ 4732 if (isPrimitive() || isArray() || Void.TYPE.equals(this)) { 4733 return new Class[] { this }; 4734 } 4735 4736 Class host = getNestHostFromAnnotation(); 4737 if (host != null && !host.equals(this)) { 4738 if (host.isPrimitive() || host.isArray() || Void.TYPE.equals(host)) { 4739 return new Class[] { this }; 4740 } 4741 return host.getNestMembers(this); 4742 } 4743 return getNestMembers(this); 4744 } 4745 getNestMembers(Class<?> originatingMember)4746 private Class<?>[] getNestMembers(Class<?> originatingMember) { 4747 4748 Class[] members = getNestMembersFromAnnotation(); 4749 if (members == null) { 4750 return new Class[] { originatingMember }; 4751 } 4752 if (originatingMember != this && !nestMembersIncludeMember(members, originatingMember)) { 4753 return new Class[] { originatingMember }; 4754 } 4755 4756 Class[] result = new Class[members.length+1]; 4757 result[0] = this; 4758 int idx = 1; 4759 for (Class m : members) { 4760 if (m == null || !this.equals(m.getNestHostFromAnnotation())) { 4761 continue; 4762 } 4763 result[idx] = m; 4764 ++idx; 4765 } 4766 4767 if (idx < result.length) { 4768 Class[] tmp = new Class[idx]; 4769 for (int i = 0; i < tmp.length; ++i) { 4770 tmp[i] = result[i]; 4771 } 4772 result = tmp; 4773 } 4774 4775 return result; 4776 } 4777 4778 @FastNative getNestMembersFromAnnotation()4779 private native Class<?>[] getNestMembersFromAnnotation(); 4780 4781 private static class Caches { 4782 /** 4783 * Cache to avoid frequent recalculation of generic interfaces, which is generally uncommon. 4784 * Sized sufficient to allow ConcurrentHashMapTest to run without recalculating its generic 4785 * interfaces (required to avoid time outs). Validated by running reflection heavy code 4786 * such as applications using Guice-like frameworks. 4787 */ 4788 private static final BasicLruCache<Class, Type[]> genericInterfaces 4789 = new BasicLruCache<Class, Type[]>(8); 4790 } 4791 4792 // Android-changed: Remove javadoc related to hidden classes and ClassDesc. 4793 /** 4794 * Returns the descriptor string of the entity (class, interface, array class, 4795 * primitive type, or {@code void}) represented by this {@code Class} object. 4796 * 4797 * <p> If this {@code Class} object represents a class or interface, 4798 * not an array class, then: 4799 * <ul> 4800 * <li> The result is a field descriptor (JVMS {@jvms 4.3.2}) 4801 * for the class or interface. 4802 * </ul> 4803 * 4804 * <p> If this {@code Class} object represents an array class, then 4805 * the result is a string consisting of one or more '{@code [}' characters 4806 * representing the depth of the array nesting, followed by the 4807 * descriptor string of the element type. 4808 * <ul> 4809 * <li> This array class can be described nominally. 4810 * </ul> 4811 * 4812 * <p> If this {@code Class} object represents a primitive type or 4813 * {@code void}, then the result is a field descriptor string which 4814 * is a one-letter code corresponding to a primitive type or {@code void} 4815 * ({@code "B", "C", "D", "F", "I", "J", "S", "Z", "V"}) (JVMS {@jvms 4.3.2}). 4816 * 4817 * @apiNote 4818 * This is not a strict inverse of {@link #forName}; 4819 * distinct classes which share a common name but have different class loaders 4820 * will have identical descriptor strings. 4821 * 4822 * @return the descriptor string for this {@code Class} object 4823 * @jvms 4.3.2 Field Descriptors 4824 * @since 12 4825 */ 4826 @Override descriptorString()4827 public String descriptorString() { 4828 if (isPrimitive()) 4829 return Wrapper.forPrimitiveType(this).basicTypeString(); 4830 4831 if (isArray()) { 4832 return "[" + componentType.descriptorString(); 4833 } else if (isHidden()) { 4834 String name = getName(); 4835 int index = name.indexOf('/'); 4836 return new StringBuilder(name.length() + 2) 4837 .append('L') 4838 .append(name.substring(0, index).replace('.', '/')) 4839 .append('.') 4840 .append(name, index + 1, name.length()) 4841 .append(';') 4842 .toString(); 4843 } else { 4844 String name = getName().replace('.', '/'); 4845 return new StringBuilder(name.length() + 2) 4846 .append('L') 4847 .append(name) 4848 .append(';') 4849 .toString(); 4850 } 4851 } 4852 4853 /** 4854 * Returns the component type of this {@code Class}, if it describes 4855 * an array type, or {@code null} otherwise. 4856 * 4857 * @implSpec 4858 * Equivalent to {@link Class#getComponentType()}. 4859 * 4860 * @return a {@code Class} describing the component type, or {@code null} 4861 * if this {@code Class} does not describe an array type 4862 * @since 12 4863 */ 4864 @Override componentType()4865 public Class<?> componentType() { 4866 return isArray() ? componentType : null; 4867 } 4868 4869 /** 4870 * Returns a {@code Class} for an array type whose component type 4871 * is described by this {@linkplain Class}. 4872 * 4873 * @return a {@code Class} describing the array type 4874 * @since 12 4875 */ 4876 @Override arrayType()4877 public Class<?> arrayType() { 4878 return Array.newInstance(this, 0).getClass(); 4879 } 4880 4881 /** 4882 * Returns a nominal descriptor for this instance, if one can be 4883 * constructed, or an empty {@link Optional} if one cannot be. 4884 * 4885 * @return An {@link Optional} containing the resulting nominal descriptor, 4886 * or an empty {@link Optional} if one cannot be constructed. 4887 * @since 12 4888 * @hide 4889 */ 4890 @Override describeConstable()4891 public Optional<ClassDesc> describeConstable() { 4892 Class<?> c = isArray() ? elementType() : this; 4893 return c.isHidden() ? Optional.empty() 4894 : Optional.of(ClassDesc.ofDescriptor(descriptorString())); 4895 } 4896 4897 /** 4898 * Returns {@code true} if and only if the underlying class is a hidden class. 4899 * 4900 * @return {@code true} if and only if this class is a hidden class. 4901 * 4902 * @since 15 4903 * @see MethodHandles.Lookup#defineHiddenClass 4904 * @hide 4905 */ 4906 // Android-changed: Android doesn't support hidden classes yet. 4907 // public native boolean isHidden(); 4908 @IntrinsicCandidate 4909 // Android-changed: Android has not implemented the hidden class feature yet. 4910 // public native boolean isHidden(); isHidden()4911 public boolean isHidden() { 4912 return false; 4913 } 4914 4915 // Android-changed: Removed @jls tags. 4916 /** 4917 * Returns an array containing {@code Class} objects representing the 4918 * direct subinterfaces or subclasses permitted to extend or 4919 * implement this class or interface if it is sealed. The order of such elements 4920 * is unspecified. The array is empty if this sealed class or interface has no 4921 * permitted subclass. If this {@code Class} object represents a primitive type, 4922 * {@code void}, an array type, or a class or interface that is not sealed, 4923 * that is {@link #isSealed()} returns {@code false}, then this method returns {@code null}. 4924 * Conversely, if {@link #isSealed()} returns {@code true}, then this method 4925 * returns a non-null value. 4926 * 4927 * For each class or interface {@code C} which is recorded as a permitted 4928 * direct subinterface or subclass of this class or interface, 4929 * this method attempts to obtain the {@code Class} 4930 * object for {@code C} (using {@linkplain #getClassLoader() the defining class 4931 * loader} of the current {@code Class} object). 4932 * The {@code Class} objects which can be obtained and which are direct 4933 * subinterfaces or subclasses of this class or interface, 4934 * are indicated by elements of the returned array. If a {@code Class} object 4935 * cannot be obtained, it is silently ignored, and not included in the result 4936 * array. 4937 * 4938 * @return an array of {@code Class} objects of the permitted subclasses of this class or interface, 4939 * or {@code null} if this class or interface is not sealed. 4940 * 4941 * @since 17 4942 */ 4943 // Android-removed: CallerSensitive annotation 4944 // @CallerSensitive getPermittedSubclasses()4945 public Class<?>[] getPermittedSubclasses() { 4946 Class<?>[] subClasses; 4947 // Android-changed: A final class cannot be sealed. 4948 // if (isArray() || isPrimitive() || (subClasses = getPermittedSubclassesFromAnnotation()) == null) { 4949 if (isArray() || isPrimitive() || Modifier.isFinal( getModifiers() ) || 4950 (subClasses = getPermittedSubclassesFromAnnotation()) == null) { 4951 return null; 4952 } 4953 // Android-changed: Avoid using lambdas. 4954 /* 4955 if (subClasses.length > 0) { 4956 if (Arrays.stream(subClasses).anyMatch(c -> !isDirectSubType(c))) { 4957 subClasses = Arrays.stream(subClasses) 4958 .filter(this::isDirectSubType) 4959 .toArray(s -> new Class<?>[s]); 4960 } 4961 } 4962 */ 4963 int directSubClassCount = getDirectSubClassCount(subClasses); 4964 if (directSubClassCount < subClasses.length) { 4965 Class[] tmp = new Class[directSubClassCount]; 4966 int idx = 0; 4967 for (Class<?> c : subClasses) { 4968 if (isDirectSubType(c)) { 4969 tmp[idx] = c; 4970 ++idx; 4971 } 4972 } 4973 subClasses = tmp; 4974 } 4975 4976 // Android-removed: SecurityManager usage. 4977 /* 4978 if (subClasses.length > 0) { 4979 // If we return some classes we need a security check: 4980 @SuppressWarnings("removal") 4981 SecurityManager sm = System.getSecurityManager(); 4982 if (sm != null) { 4983 checkPackageAccessForPermittedSubclasses(sm, 4984 ClassLoader.getClassLoader(Reflection.getCallerClass()), 4985 subClasses); 4986 } 4987 } 4988 */ 4989 return subClasses; 4990 } 4991 getDirectSubClassCount(Class<?>[] subClasses)4992 private int getDirectSubClassCount(Class<?>[] subClasses) { 4993 int result = 0; 4994 for (Class<?> c : subClasses) { 4995 if (isDirectSubType(c)) { 4996 ++result; 4997 } 4998 } 4999 return result; 5000 } 5001 isDirectSubType(Class<?> c)5002 private boolean isDirectSubType(Class<?> c) { 5003 if (isInterface()) { 5004 // Android-changed: Use of getInterfaces 5005 //for (Class<?> i : c.getInterfaces(/* cloneArray */ false)) { 5006 for (Class<?> i : c.getInterfaces()) { 5007 if (i == this) { 5008 return true; 5009 } 5010 } 5011 } else { 5012 return c.getSuperclass() == this; 5013 } 5014 return false; 5015 } 5016 5017 // Android-changed: Removed @jls tags. 5018 /** 5019 * Returns {@code true} if and only if this {@code Class} object represents 5020 * a sealed class or interface. If this {@code Class} object represents a 5021 * primitive type, {@code void}, or an array type, this method returns 5022 * {@code false}. A sealed class or interface has (possibly zero) permitted 5023 * subclasses; {@link #getPermittedSubclasses()} returns a non-null but 5024 * possibly empty value for a sealed class or interface. 5025 * 5026 * @return {@code true} if and only if this {@code Class} object represents 5027 * a sealed class or interface. 5028 * 5029 * @since 17 5030 */ isSealed()5031 public boolean isSealed() { 5032 if (isArray() || isPrimitive()) { 5033 return false; 5034 } 5035 return getPermittedSubclasses() != null; 5036 } 5037 5038 // Android-changed: Implement permitted classes on top of ART. 5039 // private native Class<?>[] getPermittedSubclasses0(); 5040 @FastNative getPermittedSubclassesFromAnnotation()5041 private native Class<?>[] getPermittedSubclassesFromAnnotation(); 5042 } 5043