1 /* 2 * Copyright (C) 2014 The Android Open Source Project 3 * Copyright (c) 1994, 2014, 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.optimization.FastNative; 30 31 import java.io.InputStream; 32 import java.io.Serializable; 33 import java.lang.annotation.Annotation; 34 import java.lang.annotation.Inherited; 35 import java.lang.reflect.AnnotatedElement; 36 import java.lang.reflect.Array; 37 import java.lang.reflect.Constructor; 38 import java.lang.reflect.Field; 39 import java.lang.reflect.GenericDeclaration; 40 import java.lang.reflect.Member; 41 import java.lang.reflect.Method; 42 import java.lang.reflect.Modifier; 43 import java.lang.reflect.Type; 44 import java.lang.reflect.TypeVariable; 45 import java.util.ArrayList; 46 import java.util.Arrays; 47 import java.util.Collection; 48 import java.util.Collections; 49 import java.util.HashMap; 50 import java.util.List; 51 import java.util.Objects; 52 import libcore.reflect.GenericSignatureParser; 53 import libcore.reflect.InternalNames; 54 import libcore.reflect.Types; 55 import libcore.util.BasicLruCache; 56 import libcore.util.CollectionUtils; 57 import libcore.util.EmptyArray; 58 59 import dalvik.system.ClassExt; 60 import sun.reflect.CallerSensitive; 61 import sun.reflect.Reflection; 62 63 /** 64 * Instances of the class {@code Class} represent classes and 65 * interfaces in a running Java application. An enum is a kind of 66 * class and an annotation is a kind of interface. Every array also 67 * belongs to a class that is reflected as a {@code Class} object 68 * that is shared by all arrays with the same element type and number 69 * of dimensions. The primitive Java types ({@code boolean}, 70 * {@code byte}, {@code char}, {@code short}, 71 * {@code int}, {@code long}, {@code float}, and 72 * {@code double}), and the keyword {@code void} are also 73 * represented as {@code Class} objects. 74 * 75 * <p> {@code Class} has no public constructor. Instead {@code Class} 76 * objects are constructed automatically by the Java Virtual Machine as classes 77 * are loaded and by calls to the {@code defineClass} method in the class 78 * loader. 79 * 80 * <p> The following example uses a {@code Class} object to print the 81 * class name of an object: 82 * 83 * <blockquote><pre> 84 * void printClassName(Object obj) { 85 * System.out.println("The class of " + obj + 86 * " is " + obj.getClass().getName()); 87 * } 88 * </pre></blockquote> 89 * 90 * <p> It is also possible to get the {@code Class} object for a named 91 * type (or for void) using a class literal. See Section 15.8.2 of 92 * <cite>The Java™ Language Specification</cite>. 93 * For example: 94 * 95 * <blockquote> 96 * {@code System.out.println("The name of class Foo is: "+Foo.class.getName());} 97 * </blockquote> 98 * 99 * @param <T> the type of the class modeled by this {@code Class} 100 * object. For example, the type of {@code String.class} is {@code 101 * Class<String>}. Use {@code Class<?>} if the class being modeled is 102 * unknown. 103 * 104 * @author unascribed 105 * @see java.lang.ClassLoader#defineClass(byte[], int, int) 106 * @since JDK1.0 107 */ 108 public final class Class<T> implements java.io.Serializable, 109 GenericDeclaration, 110 Type, 111 AnnotatedElement { 112 private static final int ANNOTATION= 0x00002000; 113 private static final int ENUM = 0x00004000; 114 private static final int SYNTHETIC = 0x00001000; 115 private static final int FINALIZABLE = 0x80000000; 116 117 /** defining class loader, or null for the "bootstrap" system loader. */ 118 private transient ClassLoader classLoader; 119 120 /** 121 * For array classes, the component class object for instanceof/checkcast (for String[][][], 122 * this will be String[][]). null for non-array classes. 123 */ 124 private transient Class<?> componentType; 125 126 /** 127 * DexCache of resolved constant pool entries. Will be null for certain runtime-generated classes 128 * e.g. arrays and primitive classes. 129 */ 130 private transient Object dexCache; 131 132 /** 133 * Extra data that only some classes possess. This is allocated lazily as needed. 134 */ 135 private transient ClassExt extData; 136 137 /** 138 * The interface table (iftable_) contains pairs of a interface class and an array of the 139 * interface methods. There is one pair per interface supported by this class. That 140 * means one pair for each interface we support directly, indirectly via superclass, or 141 * indirectly via a superinterface. This will be null if neither we nor our superclass 142 * implement any interfaces. 143 * 144 * Why we need this: given "class Foo implements Face", declare "Face faceObj = new Foo()". 145 * Invoke faceObj.blah(), where "blah" is part of the Face interface. We can't easily use a 146 * single vtable. 147 * 148 * For every interface a concrete class implements, we create an array of the concrete vtable_ 149 * methods for the methods in the interface. 150 */ 151 private transient Object[] ifTable; 152 153 /** Lazily computed name of this class; always prefer calling getName(). */ 154 private transient String name; 155 156 /** The superclass, or null if this is java.lang.Object, an interface or primitive type. */ 157 private transient Class<? super T> superClass; 158 159 /** 160 * Virtual method table (vtable), for use by "invoke-virtual". The vtable from the superclass 161 * is copied in, and virtual methods from our class either replace those from the super or are 162 * appended. For abstract classes, methods may be created in the vtable that aren't in 163 * virtual_ methods_ for miranda methods. 164 */ 165 private transient Object vtable; 166 167 /** 168 * Instance fields. These describe the layout of the contents of an Object. Note that only the 169 * fields directly declared by this class are listed in iFields; fields declared by a 170 * superclass are listed in the superclass's Class.iFields. 171 * 172 * All instance fields that refer to objects are guaranteed to be at the beginning of the field 173 * list. {@link Class#numReferenceInstanceFields} specifies the number of reference fields. 174 */ 175 private transient long iFields; 176 177 /** All methods with this class as the base for virtual dispatch. */ 178 private transient long methods; 179 180 /** Static fields */ 181 private transient long sFields; 182 183 /** access flags; low 16 bits are defined by VM spec */ 184 private transient int accessFlags; 185 186 /** Class flags to help the GC with object scanning. */ 187 private transient int classFlags; 188 189 /** 190 * Total size of the Class instance; used when allocating storage on GC heap. 191 * See also {@link Class#objectSize}. 192 */ 193 private transient int classSize; 194 195 /** 196 * tid used to check for recursive static initializer invocation. 197 */ 198 private transient int clinitThreadId; 199 200 /** 201 * Class def index from dex file. An index of 65535 indicates that there is no class definition, 202 * for example for an array type. 203 * TODO: really 16bits as type indices are 16bit. 204 */ 205 private transient int dexClassDefIndex; 206 207 /** 208 * Class type index from dex file, lazily computed. An index of 65535 indicates that the type 209 * index isn't known. Volatile to avoid double-checked locking bugs. 210 * TODO: really 16bits as type indices are 16bit. 211 */ 212 private transient volatile int dexTypeIndex; 213 214 /** Number of instance fields that are object references. */ 215 private transient int numReferenceInstanceFields; 216 217 /** Number of static fields that are object references. */ 218 private transient int numReferenceStaticFields; 219 220 /** 221 * Total object size; used when allocating storage on GC heap. For interfaces and abstract 222 * classes this will be zero. See also {@link Class#classSize}. 223 */ 224 private transient int objectSize; 225 226 /** 227 * Aligned object size for allocation fast path. The value is max int if the object is 228 * uninitialized or finalizable, otherwise the aligned object size. 229 */ 230 private transient int objectSizeAllocFastPath; 231 232 /** 233 * The lower 16 bits is the primitive type value, or 0 if not a primitive type; set for 234 * generated primitive classes. 235 */ 236 private transient int primitiveType; 237 238 /** Bitmap of offsets of iFields. */ 239 private transient int referenceInstanceOffsets; 240 241 /** State of class initialization */ 242 private transient int status; 243 244 /** Offset of the first virtual method copied from an interface in the methods array. */ 245 private transient short copiedMethodsOffset; 246 247 /** Offset of the first virtual method defined in this class in the methods array. */ 248 private transient short virtualMethodsOffset; 249 250 /* 251 * Private constructor. Only the Java Virtual Machine creates Class objects. 252 * This constructor is not used and prevents the default constructor being 253 * generated. 254 */ Class()255 private Class() {} 256 257 258 /** 259 * Converts the object to a string. The string representation is the 260 * string "class" or "interface", followed by a space, and then by the 261 * fully qualified name of the class in the format returned by 262 * {@code getName}. If this {@code Class} object represents a 263 * primitive type, this method returns the name of the primitive type. If 264 * this {@code Class} object represents void this method returns 265 * "void". 266 * 267 * @return a string representation of this class object. 268 */ toString()269 public String toString() { 270 return (isInterface() ? "interface " : (isPrimitive() ? "" : "class ")) 271 + getName(); 272 } 273 274 /** 275 * Returns a string describing this {@code Class}, including 276 * information about modifiers and type parameters. 277 * 278 * The string is formatted as a list of type modifiers, if any, 279 * followed by the kind of type (empty string for primitive types 280 * and {@code class}, {@code enum}, {@code interface}, or 281 * <code>@</code>{@code interface}, as appropriate), followed 282 * by the type's name, followed by an angle-bracketed 283 * comma-separated list of the type's type parameters, if any. 284 * 285 * A space is used to separate modifiers from one another and to 286 * separate any modifiers from the kind of type. The modifiers 287 * occur in canonical order. If there are no type parameters, the 288 * type parameter list is elided. 289 * 290 * <p>Note that since information about the runtime representation 291 * of a type is being generated, modifiers not present on the 292 * originating source code or illegal on the originating source 293 * code may be present. 294 * 295 * @return a string describing this {@code Class}, including 296 * information about modifiers and type parameters 297 * 298 * @since 1.8 299 */ toGenericString()300 public String toGenericString() { 301 if (isPrimitive()) { 302 return toString(); 303 } else { 304 StringBuilder sb = new StringBuilder(); 305 306 // Class modifiers are a superset of interface modifiers 307 int modifiers = getModifiers() & Modifier.classModifiers(); 308 if (modifiers != 0) { 309 sb.append(Modifier.toString(modifiers)); 310 sb.append(' '); 311 } 312 313 if (isAnnotation()) { 314 sb.append('@'); 315 } 316 if (isInterface()) { // Note: all annotation types are interfaces 317 sb.append("interface"); 318 } else { 319 if (isEnum()) 320 sb.append("enum"); 321 else 322 sb.append("class"); 323 } 324 sb.append(' '); 325 sb.append(getName()); 326 327 TypeVariable<?>[] typeparms = getTypeParameters(); 328 if (typeparms.length > 0) { 329 boolean first = true; 330 sb.append('<'); 331 for(TypeVariable<?> typeparm: typeparms) { 332 if (!first) 333 sb.append(','); 334 sb.append(typeparm.getTypeName()); 335 first = false; 336 } 337 sb.append('>'); 338 } 339 340 return sb.toString(); 341 } 342 } 343 344 /** 345 * Returns the {@code Class} object associated with the class or 346 * interface with the given string name. Invoking this method is 347 * equivalent to: 348 * 349 * <blockquote> 350 * {@code Class.forName(className, true, currentLoader)} 351 * </blockquote> 352 * 353 * where {@code currentLoader} denotes the defining class loader of 354 * the current class. 355 * 356 * <p> For example, the following code fragment returns the 357 * runtime {@code Class} descriptor for the class named 358 * {@code java.lang.Thread}: 359 * 360 * <blockquote> 361 * {@code Class t = Class.forName("java.lang.Thread")} 362 * </blockquote> 363 * <p> 364 * A call to {@code forName("X")} causes the class named 365 * {@code X} to be initialized. 366 * 367 * @param className the fully qualified name of the desired class. 368 * @return the {@code Class} object for the class with the 369 * specified name. 370 * @exception LinkageError if the linkage fails 371 * @exception ExceptionInInitializerError if the initialization provoked 372 * by this method fails 373 * @exception ClassNotFoundException if the class cannot be located 374 */ 375 @CallerSensitive forName(String className)376 public static Class<?> forName(String className) 377 throws ClassNotFoundException { 378 Class<?> caller = Reflection.getCallerClass(); 379 return forName(className, true, ClassLoader.getClassLoader(caller)); 380 } 381 382 383 /** 384 * Returns the {@code Class} object associated with the class or 385 * interface with the given string name, using the given class loader. 386 * Given the fully qualified name for a class or interface (in the same 387 * format returned by {@code getName}) this method attempts to 388 * locate, load, and link the class or interface. The specified class 389 * loader is used to load the class or interface. If the parameter 390 * {@code loader} is null, the class is loaded through the bootstrap 391 * class loader. The class is initialized only if the 392 * {@code initialize} parameter is {@code true} and if it has 393 * not been initialized earlier. 394 * 395 * <p> If {@code name} denotes a primitive type or void, an attempt 396 * will be made to locate a user-defined class in the unnamed package whose 397 * name is {@code name}. Therefore, this method cannot be used to 398 * obtain any of the {@code Class} objects representing primitive 399 * types or void. 400 * 401 * <p> If {@code name} denotes an array class, the component type of 402 * the array class is loaded but not initialized. 403 * 404 * <p> For example, in an instance method the expression: 405 * 406 * <blockquote> 407 * {@code Class.forName("Foo")} 408 * </blockquote> 409 * 410 * is equivalent to: 411 * 412 * <blockquote> 413 * {@code Class.forName("Foo", true, this.getClass().getClassLoader())} 414 * </blockquote> 415 * 416 * Note that this method throws errors related to loading, linking or 417 * initializing as specified in Sections 12.2, 12.3 and 12.4 of <em>The 418 * Java Language Specification</em>. 419 * Note that this method does not check whether the requested class 420 * is accessible to its caller. 421 * 422 * <p> If the {@code loader} is {@code null}, and a security 423 * manager is present, and the caller's class loader is not null, then this 424 * method calls the security manager's {@code checkPermission} method 425 * with a {@code RuntimePermission("getClassLoader")} permission to 426 * ensure it's ok to access the bootstrap class loader. 427 * 428 * @param name fully qualified name of the desired class 429 * @param initialize if {@code true} the class will be initialized. 430 * See Section 12.4 of <em>The Java Language Specification</em>. 431 * @param loader class loader from which the class must be loaded 432 * @return class object representing the desired class 433 * 434 * @exception LinkageError if the linkage fails 435 * @exception ExceptionInInitializerError if the initialization provoked 436 * by this method fails 437 * @exception ClassNotFoundException if the class cannot be located by 438 * the specified class loader 439 * 440 * @see java.lang.Class#forName(String) 441 * @see java.lang.ClassLoader 442 * @since 1.2 443 */ 444 @CallerSensitive forName(String name, boolean initialize, ClassLoader loader)445 public static Class<?> forName(String name, boolean initialize, 446 ClassLoader loader) 447 throws ClassNotFoundException 448 { 449 if (loader == null) { 450 loader = BootClassLoader.getInstance(); 451 } 452 Class<?> result; 453 try { 454 result = classForName(name, initialize, loader); 455 } catch (ClassNotFoundException e) { 456 Throwable cause = e.getCause(); 457 if (cause instanceof LinkageError) { 458 throw (LinkageError) cause; 459 } 460 throw e; 461 } 462 return result; 463 } 464 465 /** Called after security checks have been made. */ 466 @FastNative classForName(String className, boolean shouldInitialize, ClassLoader classLoader)467 static native Class<?> classForName(String className, boolean shouldInitialize, 468 ClassLoader classLoader) throws ClassNotFoundException; 469 470 /** 471 * Creates a new instance of the class represented by this {@code Class} 472 * object. The class is instantiated as if by a {@code new} 473 * expression with an empty argument list. The class is initialized if it 474 * has not already been initialized. 475 * 476 * <p>Note that this method propagates any exception thrown by the 477 * nullary constructor, including a checked exception. Use of 478 * this method effectively bypasses the compile-time exception 479 * checking that would otherwise be performed by the compiler. 480 * The {@link 481 * java.lang.reflect.Constructor#newInstance(java.lang.Object...) 482 * Constructor.newInstance} method avoids this problem by wrapping 483 * any exception thrown by the constructor in a (checked) {@link 484 * java.lang.reflect.InvocationTargetException}. 485 * 486 * @return a newly allocated instance of the class represented by this 487 * object. 488 * @throws IllegalAccessException if the class or its nullary 489 * constructor is not accessible. 490 * @throws InstantiationException 491 * if this {@code Class} represents an abstract class, 492 * an interface, an array class, a primitive type, or void; 493 * or if the class has no nullary constructor; 494 * or if the instantiation fails for some other reason. 495 * @throws ExceptionInInitializerError if the initialization 496 * provoked by this method fails. 497 * @throws SecurityException 498 * If a security manager, <i>s</i>, is present and 499 * the caller's class loader is not the same as or an 500 * ancestor of the class loader for the current class and 501 * invocation of {@link SecurityManager#checkPackageAccess 502 * s.checkPackageAccess()} denies access to the package 503 * of this class. 504 */ 505 @FastNative newInstance()506 public native T newInstance() throws InstantiationException, IllegalAccessException; 507 508 /** 509 * Determines if the specified {@code Object} is assignment-compatible 510 * with the object represented by this {@code Class}. This method is 511 * the dynamic equivalent of the Java language {@code instanceof} 512 * operator. The method returns {@code true} if the specified 513 * {@code Object} argument is non-null and can be cast to the 514 * reference type represented by this {@code Class} object without 515 * raising a {@code ClassCastException.} It returns {@code false} 516 * otherwise. 517 * 518 * <p> Specifically, if this {@code Class} object represents a 519 * declared class, this method returns {@code true} if the specified 520 * {@code Object} argument is an instance of the represented class (or 521 * of any of its subclasses); it returns {@code false} otherwise. If 522 * this {@code Class} object represents an array class, this method 523 * returns {@code true} if the specified {@code Object} argument 524 * can be converted to an object of the array class by an identity 525 * conversion or by a widening reference conversion; it returns 526 * {@code false} otherwise. If this {@code Class} object 527 * represents an interface, this method returns {@code true} if the 528 * class or any superclass of the specified {@code Object} argument 529 * implements this interface; it returns {@code false} otherwise. If 530 * this {@code Class} object represents a primitive type, this method 531 * returns {@code false}. 532 * 533 * @param obj the object to check 534 * @return true if {@code obj} is an instance of this class 535 * 536 * @since JDK1.1 537 */ isInstance(Object obj)538 public boolean isInstance(Object obj) { 539 if (obj == null) { 540 return false; 541 } 542 return isAssignableFrom(obj.getClass()); 543 } 544 545 546 /** 547 * Determines if the class or interface represented by this 548 * {@code Class} object is either the same as, or is a superclass or 549 * superinterface of, the class or interface represented by the specified 550 * {@code Class} parameter. It returns {@code true} if so; 551 * otherwise it returns {@code false}. If this {@code Class} 552 * object represents a primitive type, this method returns 553 * {@code true} if the specified {@code Class} parameter is 554 * exactly this {@code Class} object; otherwise it returns 555 * {@code false}. 556 * 557 * <p> Specifically, this method tests whether the type represented by the 558 * specified {@code Class} parameter can be converted to the type 559 * represented by this {@code Class} object via an identity conversion 560 * or via a widening reference conversion. See <em>The Java Language 561 * Specification</em>, sections 5.1.1 and 5.1.4 , for details. 562 * 563 * @param cls the {@code Class} object to be checked 564 * @return the {@code boolean} value indicating whether objects of the 565 * type {@code cls} can be assigned to objects of this class 566 * @exception NullPointerException if the specified Class parameter is 567 * null. 568 * @since JDK1.1 569 */ isAssignableFrom(Class<?> cls)570 public boolean isAssignableFrom(Class<?> cls) { 571 if (this == cls) { 572 return true; // Can always assign to things of the same type. 573 } else if (this == Object.class) { 574 return !cls.isPrimitive(); // Can assign any reference to java.lang.Object. 575 } else if (isArray()) { 576 return cls.isArray() && componentType.isAssignableFrom(cls.componentType); 577 } else if (isInterface()) { 578 // Search iftable which has a flattened and uniqued list of interfaces. 579 Object[] iftable = cls.ifTable; 580 if (iftable != null) { 581 for (int i = 0; i < iftable.length; i += 2) { 582 if (iftable[i] == this) { 583 return true; 584 } 585 } 586 } 587 return false; 588 } else { 589 if (!cls.isInterface()) { 590 for (cls = cls.superClass; cls != null; cls = cls.superClass) { 591 if (cls == this) { 592 return true; 593 } 594 } 595 } 596 return false; 597 } 598 } 599 600 /** 601 * Determines if the specified {@code Class} object represents an 602 * interface type. 603 * 604 * @return {@code true} if this object represents an interface; 605 * {@code false} otherwise. 606 */ isInterface()607 public boolean isInterface() { 608 return (accessFlags & Modifier.INTERFACE) != 0; 609 } 610 611 /** 612 * Determines if this {@code Class} object represents an array class. 613 * 614 * @return {@code true} if this object represents an array class; 615 * {@code false} otherwise. 616 * @since JDK1.1 617 */ isArray()618 public boolean isArray() { 619 return getComponentType() != null; 620 } 621 622 /** 623 * Determines if the specified {@code Class} object represents a 624 * primitive type. 625 * 626 * <p> There are nine predefined {@code Class} objects to represent 627 * the eight primitive types and void. These are created by the Java 628 * Virtual Machine, and have the same names as the primitive types that 629 * they represent, namely {@code boolean}, {@code byte}, 630 * {@code char}, {@code short}, {@code int}, 631 * {@code long}, {@code float}, and {@code double}. 632 * 633 * <p> These objects may only be accessed via the following public static 634 * final variables, and are the only {@code Class} objects for which 635 * this method returns {@code true}. 636 * 637 * @return true if and only if this class represents a primitive type 638 * 639 * @see java.lang.Boolean#TYPE 640 * @see java.lang.Character#TYPE 641 * @see java.lang.Byte#TYPE 642 * @see java.lang.Short#TYPE 643 * @see java.lang.Integer#TYPE 644 * @see java.lang.Long#TYPE 645 * @see java.lang.Float#TYPE 646 * @see java.lang.Double#TYPE 647 * @see java.lang.Void#TYPE 648 * @since JDK1.1 649 */ isPrimitive()650 public boolean isPrimitive() { 651 return (primitiveType & 0xFFFF) != 0; 652 } 653 654 /** 655 * Indicates whether this {@code Class} or its parents override finalize. 656 * 657 * @return {@code true} if and if this class or its parents override 658 * finalize; 659 * 660 * @hide 661 */ isFinalizable()662 public boolean isFinalizable() { 663 return (getModifiers() & FINALIZABLE) != 0; 664 } 665 666 /** 667 * Returns true if this {@code Class} object represents an annotation 668 * type. Note that if this method returns true, {@link #isInterface()} 669 * would also return true, as all annotation types are also interfaces. 670 * 671 * @return {@code true} if this class object represents an annotation 672 * type; {@code false} otherwise 673 * @since 1.5 674 */ isAnnotation()675 public boolean isAnnotation() { 676 return (getModifiers() & ANNOTATION) != 0; 677 } 678 679 /** 680 * Returns {@code true} if this class is a synthetic class; 681 * returns {@code false} otherwise. 682 * @return {@code true} if and only if this class is a synthetic class as 683 * defined by the Java Language Specification. 684 * @jls 13.1 The Form of a Binary 685 * @since 1.5 686 */ isSynthetic()687 public boolean isSynthetic() { 688 return (getModifiers() & SYNTHETIC) != 0; 689 } 690 691 /** 692 * Returns the name of the entity (class, interface, array class, 693 * primitive type, or void) represented by this {@code Class} object, 694 * as a {@code String}. 695 * 696 * <p> If this class object represents a reference type that is not an 697 * array type then the binary name of the class is returned, as specified 698 * by 699 * <cite>The Java™ Language Specification</cite>. 700 * 701 * <p> If this class object represents a primitive type or void, then the 702 * name returned is a {@code String} equal to the Java language 703 * keyword corresponding to the primitive type or void. 704 * 705 * <p> If this class object represents a class of arrays, then the internal 706 * form of the name consists of the name of the element type preceded by 707 * one or more '{@code [}' characters representing the depth of the array 708 * nesting. The encoding of element type names is as follows: 709 * 710 * <blockquote><table summary="Element types and encodings"> 711 * <tr><th> Element Type <th> <th> Encoding 712 * <tr><td> boolean <td> <td align=center> Z 713 * <tr><td> byte <td> <td align=center> B 714 * <tr><td> char <td> <td align=center> C 715 * <tr><td> class or interface 716 * <td> <td align=center> L<i>classname</i>; 717 * <tr><td> double <td> <td align=center> D 718 * <tr><td> float <td> <td align=center> F 719 * <tr><td> int <td> <td align=center> I 720 * <tr><td> long <td> <td align=center> J 721 * <tr><td> short <td> <td align=center> S 722 * </table></blockquote> 723 * 724 * <p> The class or interface name <i>classname</i> is the binary name of 725 * the class specified above. 726 * 727 * <p> Examples: 728 * <blockquote><pre> 729 * String.class.getName() 730 * returns "java.lang.String" 731 * byte.class.getName() 732 * returns "byte" 733 * (new Object[3]).getClass().getName() 734 * returns "[Ljava.lang.Object;" 735 * (new int[3][4][5][6][7][8][9]).getClass().getName() 736 * returns "[[[[[[[I" 737 * </pre></blockquote> 738 * 739 * @return the name of the class or interface 740 * represented by this object. 741 */ getName()742 public String getName() { 743 String name = this.name; 744 if (name == null) 745 this.name = name = getNameNative(); 746 return name; 747 } 748 749 @FastNative getNameNative()750 private native String getNameNative(); 751 752 /** 753 * Returns the class loader for the class. Some implementations may use 754 * null to represent the bootstrap class loader. This method will return 755 * null in such implementations if this class was loaded by the bootstrap 756 * class loader. 757 * 758 * <p> If a security manager is present, and the caller's class loader is 759 * not null and the caller's class loader is not the same as or an ancestor of 760 * the class loader for the class whose class loader is requested, then 761 * this method calls the security manager's {@code checkPermission} 762 * method with a {@code RuntimePermission("getClassLoader")} 763 * permission to ensure it's ok to access the class loader for the class. 764 * 765 * <p>If this object 766 * represents a primitive type or void, null is returned. 767 * 768 * @return the class loader that loaded the class or interface 769 * represented by this object. 770 * @throws SecurityException 771 * if a security manager exists and its 772 * {@code checkPermission} method denies 773 * access to the class loader for the class. 774 * @see java.lang.ClassLoader 775 * @see SecurityManager#checkPermission 776 * @see java.lang.RuntimePermission 777 */ getClassLoader()778 public ClassLoader getClassLoader() { 779 if (isPrimitive()) { 780 return null; 781 } 782 // Android-note: The RI returns null in the case where Android returns BootClassLoader. 783 // Noted in http://b/111850480#comment3 784 return (classLoader == null) ? BootClassLoader.getInstance() : classLoader; 785 } 786 787 /** 788 * Returns an array of {@code TypeVariable} objects that represent the 789 * type variables declared by the generic declaration represented by this 790 * {@code GenericDeclaration} object, in declaration order. Returns an 791 * array of length 0 if the underlying generic declaration declares no type 792 * variables. 793 * 794 * @return an array of {@code TypeVariable} objects that represent 795 * the type variables declared by this generic declaration 796 * @throws java.lang.reflect.GenericSignatureFormatError if the generic 797 * signature of this generic declaration does not conform to 798 * the format specified in 799 * <cite>The Java™ Virtual Machine Specification</cite> 800 * @since 1.5 801 */ 802 @Override getTypeParameters()803 public synchronized TypeVariable<Class<T>>[] getTypeParameters() { 804 String annotationSignature = getSignatureAttribute(); 805 if (annotationSignature == null) { 806 return EmptyArray.TYPE_VARIABLE; 807 } 808 GenericSignatureParser parser = new GenericSignatureParser(getClassLoader()); 809 parser.parseForClass(this, annotationSignature); 810 return parser.formalTypeParameters; 811 } 812 813 814 /** 815 * Returns the {@code Class} representing the superclass of the entity 816 * (class, interface, primitive type or void) represented by this 817 * {@code Class}. If this {@code Class} represents either the 818 * {@code Object} class, an interface, a primitive type, or void, then 819 * null is returned. If this object represents an array class then the 820 * {@code Class} object representing the {@code Object} class is 821 * returned. 822 * 823 * @return the superclass of the class represented by this object. 824 */ getSuperclass()825 public Class<? super T> getSuperclass() { 826 // For interfaces superClass is Object (which agrees with the JNI spec) 827 // but not with the expected behavior here. 828 if (isInterface()) { 829 return null; 830 } else { 831 return superClass; 832 } 833 } 834 835 /** 836 * Returns the {@code Type} representing the direct superclass of 837 * the entity (class, interface, primitive type or void) represented by 838 * this {@code Class}. 839 * 840 * <p>If the superclass is a parameterized type, the {@code Type} 841 * object returned must accurately reflect the actual type 842 * parameters used in the source code. The parameterized type 843 * representing the superclass is created if it had not been 844 * created before. See the declaration of {@link 845 * java.lang.reflect.ParameterizedType ParameterizedType} for the 846 * semantics of the creation process for parameterized types. If 847 * this {@code Class} represents either the {@code Object} 848 * class, an interface, a primitive type, or void, then null is 849 * returned. If this object represents an array class then the 850 * {@code Class} object representing the {@code Object} class is 851 * returned. 852 * 853 * @throws java.lang.reflect.GenericSignatureFormatError if the generic 854 * class signature does not conform to the format specified in 855 * <cite>The Java™ Virtual Machine Specification</cite> 856 * @throws TypeNotPresentException if the generic superclass 857 * refers to a non-existent type declaration 858 * @throws java.lang.reflect.MalformedParameterizedTypeException if the 859 * generic superclass refers to a parameterized type that cannot be 860 * instantiated for any reason 861 * @return the superclass of the class represented by this object 862 * @since 1.5 863 */ getGenericSuperclass()864 public Type getGenericSuperclass() { 865 Type genericSuperclass = getSuperclass(); 866 // This method is specified to return null for all cases where getSuperclass 867 // returns null, i.e, for primitives, interfaces, void and java.lang.Object. 868 if (genericSuperclass == null) { 869 return null; 870 } 871 872 String annotationSignature = getSignatureAttribute(); 873 if (annotationSignature != null) { 874 GenericSignatureParser parser = new GenericSignatureParser(getClassLoader()); 875 parser.parseForClass(this, annotationSignature); 876 genericSuperclass = parser.superclassType; 877 } 878 return Types.getType(genericSuperclass); 879 } 880 881 /** 882 * Gets the package for this class. The class loader of this class is used 883 * to find the package. If the class was loaded by the bootstrap class 884 * loader the set of packages loaded from CLASSPATH is searched to find the 885 * package of the class. Null is returned if no package object was created 886 * by the class loader of this class. 887 * 888 * <p> Packages have attributes for versions and specifications only if the 889 * information was defined in the manifests that accompany the classes, and 890 * if the class loader created the package instance with the attributes 891 * from the manifest. 892 * 893 * @return the package of the class, or null if no package 894 * information is available from the archive or codebase. 895 */ getPackage()896 public Package getPackage() { 897 ClassLoader loader = getClassLoader(); 898 if (loader != null) { 899 String packageName = getPackageName(); 900 return packageName != null ? loader.getPackage(packageName) : null; 901 } 902 return null; 903 } 904 905 /** 906 * Returns the fully qualified package name. 907 * 908 * <p> If this class is a top level class, then this method returns the fully 909 * qualified name of the package that the class is a member of, or the 910 * empty string if the class is in an unnamed package. 911 * 912 * <p> If this class is a member class, then this method is equivalent to 913 * invoking {@code getPackageName()} on the {@linkplain #getEnclosingClass 914 * enclosing class}. 915 * 916 * <p> If this class is a {@linkplain #isLocalClass local class} or an {@linkplain 917 * #isAnonymousClass() anonymous class}, then this method is equivalent to 918 * invoking {@code getPackageName()} on the {@linkplain #getDeclaringClass 919 * declaring class} of the {@linkplain #getEnclosingMethod enclosing method} or 920 * {@linkplain #getEnclosingConstructor enclosing constructor}. 921 * 922 * <p> If this class represents an array type then this method returns the 923 * package name of the element type. If this class represents a primitive 924 * type or void then the package name "{@code java.lang}" is returned. 925 * 926 * @return the fully qualified package name 927 * 928 * @since 9 929 * @spec JPMS 930 * @jls 6.7 Fully Qualified Names 931 */ getPackageName()932 public String getPackageName() { 933 // BEGIN Android-changed: Don't use a private field as a cache. 934 Class<?> c = this; 935 while (c.isArray()) { 936 c = c.getComponentType(); 937 } 938 if (c.isPrimitive()) { 939 return "java.lang"; 940 } else { 941 String cn = c.getName(); 942 int dot = cn.lastIndexOf('.'); 943 return (dot != -1) ? cn.substring(0, dot).intern() : ""; 944 } 945 // END Android-changed: Don't use a private field as a cache. 946 } 947 948 949 /** 950 * Determines the interfaces implemented by the class or interface 951 * represented by this object. 952 * 953 * <p> If this object represents a class, the return value is an array 954 * containing objects representing all interfaces implemented by the 955 * class. The order of the interface objects in the array corresponds to 956 * the order of the interface names in the {@code implements} clause 957 * of the declaration of the class represented by this object. For 958 * example, given the declaration: 959 * <blockquote> 960 * {@code class Shimmer implements FloorWax, DessertTopping { ... }} 961 * </blockquote> 962 * suppose the value of {@code s} is an instance of 963 * {@code Shimmer}; the value of the expression: 964 * <blockquote> 965 * {@code s.getClass().getInterfaces()[0]} 966 * </blockquote> 967 * is the {@code Class} object that represents interface 968 * {@code FloorWax}; and the value of: 969 * <blockquote> 970 * {@code s.getClass().getInterfaces()[1]} 971 * </blockquote> 972 * is the {@code Class} object that represents interface 973 * {@code DessertTopping}. 974 * 975 * <p> If this object represents an interface, the array contains objects 976 * representing all interfaces extended by the interface. The order of the 977 * interface objects in the array corresponds to the order of the interface 978 * names in the {@code extends} clause of the declaration of the 979 * interface represented by this object. 980 * 981 * <p> If this object represents a class or interface that implements no 982 * interfaces, the method returns an array of length 0. 983 * 984 * <p> If this object represents a primitive type or void, the method 985 * returns an array of length 0. 986 * 987 * <p> If this {@code Class} object represents an array type, the 988 * interfaces {@code Cloneable} and {@code java.io.Serializable} are 989 * returned in that order. 990 * 991 * @return an array of interfaces implemented by this class. 992 */ getInterfaces()993 public Class<?>[] getInterfaces() { 994 if (isArray()) { 995 return new Class<?>[] { Cloneable.class, Serializable.class }; 996 } 997 998 final Class<?>[] ifaces = getInterfacesInternal(); 999 if (ifaces == null) { 1000 return EmptyArray.CLASS; 1001 } 1002 1003 return ifaces; 1004 } 1005 1006 @FastNative getInterfacesInternal()1007 private native Class<?>[] getInterfacesInternal(); 1008 1009 1010 /** 1011 * Returns the {@code Type}s representing the interfaces 1012 * directly implemented by the class or interface represented by 1013 * this object. 1014 * 1015 * <p>If a superinterface is a parameterized type, the 1016 * {@code Type} object returned for it must accurately reflect 1017 * the actual type parameters used in the source code. The 1018 * parameterized type representing each superinterface is created 1019 * if it had not been created before. See the declaration of 1020 * {@link java.lang.reflect.ParameterizedType ParameterizedType} 1021 * for the semantics of the creation process for parameterized 1022 * types. 1023 * 1024 * <p> If this object represents a class, the return value is an 1025 * array containing objects representing all interfaces 1026 * implemented by the class. The order of the interface objects in 1027 * the array corresponds to the order of the interface names in 1028 * the {@code implements} clause of the declaration of the class 1029 * represented by this object. In the case of an array class, the 1030 * interfaces {@code Cloneable} and {@code Serializable} are 1031 * returned in that order. 1032 * 1033 * <p>If this object represents an interface, the array contains 1034 * objects representing all interfaces directly extended by the 1035 * interface. The order of the interface objects in the array 1036 * corresponds to the order of the interface names in the 1037 * {@code extends} clause of the declaration of the interface 1038 * represented by this object. 1039 * 1040 * <p>If this object represents a class or interface that 1041 * implements no interfaces, the method returns an array of length 1042 * 0. 1043 * 1044 * <p>If this object represents a primitive type or void, the 1045 * method returns an array of length 0. 1046 * 1047 * @throws java.lang.reflect.GenericSignatureFormatError 1048 * if the generic class signature does not conform to the format 1049 * specified in 1050 * <cite>The Java™ Virtual Machine Specification</cite> 1051 * @throws TypeNotPresentException if any of the generic 1052 * superinterfaces refers to a non-existent type declaration 1053 * @throws java.lang.reflect.MalformedParameterizedTypeException 1054 * if any of the generic superinterfaces refer to a parameterized 1055 * type that cannot be instantiated for any reason 1056 * @return an array of interfaces implemented by this class 1057 * @since 1.5 1058 */ getGenericInterfaces()1059 public Type[] getGenericInterfaces() { 1060 Type[] result; 1061 synchronized (Caches.genericInterfaces) { 1062 result = Caches.genericInterfaces.get(this); 1063 if (result == null) { 1064 String annotationSignature = getSignatureAttribute(); 1065 if (annotationSignature == null) { 1066 result = getInterfaces(); 1067 } else { 1068 GenericSignatureParser parser = new GenericSignatureParser(getClassLoader()); 1069 parser.parseForClass(this, annotationSignature); 1070 result = Types.getTypeArray(parser.interfaceTypes, false); 1071 } 1072 Caches.genericInterfaces.put(this, result); 1073 } 1074 } 1075 return (result.length == 0) ? result : result.clone(); 1076 } 1077 1078 1079 /** 1080 * Returns the {@code Class} representing the component type of an 1081 * array. If this class does not represent an array class this method 1082 * returns null. 1083 * 1084 * @return the {@code Class} representing the component type of this 1085 * class if this class is an array 1086 * @see java.lang.reflect.Array 1087 * @since JDK1.1 1088 */ getComponentType()1089 public Class<?> getComponentType() { 1090 return componentType; 1091 } 1092 1093 /** 1094 * Returns the Java language modifiers for this class or interface, encoded 1095 * in an integer. The modifiers consist of the Java Virtual Machine's 1096 * constants for {@code public}, {@code protected}, 1097 * {@code private}, {@code final}, {@code static}, 1098 * {@code abstract} and {@code interface}; they should be decoded 1099 * using the methods of class {@code Modifier}. 1100 * 1101 * <p> If the underlying class is an array class, then its 1102 * {@code public}, {@code private} and {@code protected} 1103 * modifiers are the same as those of its component type. If this 1104 * {@code Class} represents a primitive type or void, its 1105 * {@code public} modifier is always {@code true}, and its 1106 * {@code protected} and {@code private} modifiers are always 1107 * {@code false}. If this object represents an array class, a 1108 * primitive type or void, then its {@code final} modifier is always 1109 * {@code true} and its interface modifier is always 1110 * {@code false}. The values of its other modifiers are not determined 1111 * by this specification. 1112 * 1113 * <p> The modifier encodings are defined in <em>The Java Virtual Machine 1114 * Specification</em>, table 4.1. 1115 * 1116 * @return the {@code int} representing the modifiers for this class 1117 * @see java.lang.reflect.Modifier 1118 * @since JDK1.1 1119 */ getModifiers()1120 public int getModifiers() { 1121 // Array classes inherit modifiers from their component types, but in the case of arrays 1122 // of an inner class, the class file may contain "fake" access flags because it's not valid 1123 // for a top-level class to private, say. The real access flags are stored in the InnerClass 1124 // attribute, so we need to make sure we drill down to the inner class: the accessFlags 1125 // field is not the value we want to return, and the synthesized array class does not itself 1126 // have an InnerClass attribute. https://code.google.com/p/android/issues/detail?id=56267 1127 if (isArray()) { 1128 int componentModifiers = getComponentType().getModifiers(); 1129 if ((componentModifiers & Modifier.INTERFACE) != 0) { 1130 componentModifiers &= ~(Modifier.INTERFACE | Modifier.STATIC); 1131 } 1132 return Modifier.ABSTRACT | Modifier.FINAL | componentModifiers; 1133 } 1134 int JAVA_FLAGS_MASK = 0xffff; 1135 int modifiers = this.getInnerClassFlags(accessFlags & JAVA_FLAGS_MASK); 1136 return modifiers & JAVA_FLAGS_MASK; 1137 } 1138 1139 /** 1140 * Gets the signers of this class. 1141 * 1142 * @return the signers of this class, or null if there are no signers. In 1143 * particular, this method returns null if this object represents 1144 * a primitive type or void. 1145 * @since JDK1.1 1146 */ getSigners()1147 public Object[] getSigners() { 1148 return null; 1149 } 1150 1151 @FastNative getEnclosingMethodNative()1152 private native Method getEnclosingMethodNative(); 1153 1154 /** 1155 * If this {@code Class} object represents a local or anonymous 1156 * class within a method, returns a {@link 1157 * java.lang.reflect.Method Method} object representing the 1158 * immediately enclosing method of the underlying class. Returns 1159 * {@code null} otherwise. 1160 * 1161 * In particular, this method returns {@code null} if the underlying 1162 * class is a local or anonymous class immediately enclosed by a type 1163 * declaration, instance initializer or static initializer. 1164 * 1165 * @return the immediately enclosing method of the underlying class, if 1166 * that class is a local or anonymous class; otherwise {@code null}. 1167 * @since 1.5 1168 */ 1169 // Android-changed: Removed SecurityException. getEnclosingMethod()1170 public Method getEnclosingMethod() { 1171 if (classNameImpliesTopLevel()) { 1172 return null; 1173 } 1174 return getEnclosingMethodNative(); 1175 } 1176 1177 /** 1178 * If this {@code Class} object represents a local or anonymous 1179 * class within a constructor, returns a {@link 1180 * java.lang.reflect.Constructor Constructor} object representing 1181 * the immediately enclosing constructor of the underlying 1182 * class. Returns {@code null} otherwise. In particular, this 1183 * method returns {@code null} if the underlying class is a local 1184 * or anonymous class immediately enclosed by a type declaration, 1185 * instance initializer or static initializer. 1186 * 1187 * @return the immediately enclosing constructor of the underlying class, if 1188 * that class is a local or anonymous class; otherwise {@code null}. 1189 * @since 1.5 1190 */ 1191 // Android-changed: Removed SecurityException. getEnclosingConstructor()1192 public Constructor<?> getEnclosingConstructor() { 1193 if (classNameImpliesTopLevel()) { 1194 return null; 1195 } 1196 return getEnclosingConstructorNative(); 1197 } 1198 1199 @FastNative getEnclosingConstructorNative()1200 private native Constructor<?> getEnclosingConstructorNative(); 1201 classNameImpliesTopLevel()1202 private boolean classNameImpliesTopLevel() { 1203 return !getName().contains("$"); 1204 } 1205 1206 1207 /** 1208 * If the class or interface represented by this {@code Class} object 1209 * is a member of another class, returns the {@code Class} object 1210 * representing the class in which it was declared. This method returns 1211 * null if this class or interface is not a member of any other class. If 1212 * this {@code Class} object represents an array class, a primitive 1213 * type, or void,then this method returns null. 1214 * 1215 * @return the declaring class for this class 1216 * @since JDK1.1 1217 */ 1218 // Android-changed: Removed SecurityException. 1219 @FastNative getDeclaringClass()1220 public native Class<?> getDeclaringClass(); 1221 1222 /** 1223 * Returns the immediately enclosing class of the underlying 1224 * class. If the underlying class is a top level class this 1225 * method returns {@code null}. 1226 * @return the immediately enclosing class of the underlying class 1227 * @since 1.5 1228 */ 1229 // Android-changed: Removed SecurityException. 1230 @FastNative getEnclosingClass()1231 public native Class<?> getEnclosingClass(); 1232 1233 /** 1234 * Returns the simple name of the underlying class as given in the 1235 * source code. Returns an empty string if the underlying class is 1236 * anonymous. 1237 * 1238 * <p>The simple name of an array is the simple name of the 1239 * component type with "[]" appended. In particular the simple 1240 * name of an array whose component type is anonymous is "[]". 1241 * 1242 * @return the simple name of the underlying class 1243 * @since 1.5 1244 */ getSimpleName()1245 public String getSimpleName() { 1246 if (isArray()) 1247 return getComponentType().getSimpleName()+"[]"; 1248 1249 if (isAnonymousClass()) { 1250 return ""; 1251 } 1252 1253 if (isMemberClass() || isLocalClass()) { 1254 // Note that we obtain this information from getInnerClassName(), which uses 1255 // dex system annotations to obtain the name. It is possible for this information 1256 // to disagree with the actual enclosing class name. For example, if dex 1257 // manipulation tools have renamed the enclosing class without adjusting 1258 // the system annotation to match. See http://b/28800927. 1259 return getInnerClassName(); 1260 } 1261 1262 String simpleName = getName(); 1263 final int dot = simpleName.lastIndexOf("."); 1264 if (dot > 0) { 1265 return simpleName.substring(simpleName.lastIndexOf(".")+1); // strip the package name 1266 } 1267 1268 return simpleName; 1269 } 1270 1271 /** 1272 * Return an informative string for the name of this type. 1273 * 1274 * @return an informative string for the name of this type 1275 * @since 1.8 1276 */ getTypeName()1277 public String getTypeName() { 1278 if (isArray()) { 1279 try { 1280 Class<?> cl = this; 1281 int dimensions = 0; 1282 while (cl.isArray()) { 1283 dimensions++; 1284 cl = cl.getComponentType(); 1285 } 1286 StringBuilder sb = new StringBuilder(); 1287 sb.append(cl.getName()); 1288 for (int i = 0; i < dimensions; i++) { 1289 sb.append("[]"); 1290 } 1291 return sb.toString(); 1292 } catch (Throwable e) { /*FALLTHRU*/ } 1293 } 1294 return getName(); 1295 } 1296 1297 /** 1298 * Returns the canonical name of the underlying class as 1299 * defined by the Java Language Specification. Returns null if 1300 * the underlying class does not have a canonical name (i.e., if 1301 * it is a local or anonymous class or an array whose component 1302 * type does not have a canonical name). 1303 * @return the canonical name of the underlying class if it exists, and 1304 * {@code null} otherwise. 1305 * @since 1.5 1306 */ getCanonicalName()1307 public String getCanonicalName() { 1308 if (isArray()) { 1309 String canonicalName = getComponentType().getCanonicalName(); 1310 if (canonicalName != null) 1311 return canonicalName + "[]"; 1312 else 1313 return null; 1314 } 1315 if (isLocalOrAnonymousClass()) 1316 return null; 1317 Class<?> enclosingClass = getEnclosingClass(); 1318 if (enclosingClass == null) { // top level class 1319 return getName(); 1320 } else { 1321 String enclosingName = enclosingClass.getCanonicalName(); 1322 if (enclosingName == null) 1323 return null; 1324 return enclosingName + "." + getSimpleName(); 1325 } 1326 } 1327 1328 /** 1329 * Returns {@code true} if and only if the underlying class 1330 * is an anonymous class. 1331 * 1332 * @return {@code true} if and only if this class is an anonymous class. 1333 * @since 1.5 1334 */ 1335 @FastNative isAnonymousClass()1336 public native boolean isAnonymousClass(); 1337 1338 /** 1339 * Returns {@code true} if and only if the underlying class 1340 * is a local class. 1341 * 1342 * @return {@code true} if and only if this class is a local class. 1343 * @since 1.5 1344 */ isLocalClass()1345 public boolean isLocalClass() { 1346 return (getEnclosingMethod() != null || getEnclosingConstructor() != null) 1347 && !isAnonymousClass(); 1348 } 1349 1350 /** 1351 * Returns {@code true} if and only if the underlying class 1352 * is a member class. 1353 * 1354 * @return {@code true} if and only if this class is a member class. 1355 * @since 1.5 1356 */ isMemberClass()1357 public boolean isMemberClass() { 1358 return getDeclaringClass() != null; 1359 } 1360 1361 /** 1362 * Returns {@code true} if this is a local class or an anonymous 1363 * class. Returns {@code false} otherwise. 1364 */ isLocalOrAnonymousClass()1365 private boolean isLocalOrAnonymousClass() { 1366 // JVM Spec 4.8.6: A class must have an EnclosingMethod 1367 // attribute if and only if it is a local class or an 1368 // anonymous class. 1369 return isLocalClass() || isAnonymousClass(); 1370 } 1371 1372 /** 1373 * Returns an array containing {@code Class} objects representing all 1374 * the public classes and interfaces that are members of the class 1375 * represented by this {@code Class} object. This includes public 1376 * class and interface members inherited from superclasses and public class 1377 * and interface members declared by the class. This method returns an 1378 * array of length 0 if this {@code Class} object has no public member 1379 * classes or interfaces. This method also returns an array of length 0 if 1380 * this {@code Class} object represents a primitive type, an array 1381 * class, or void. 1382 * 1383 * @return the array of {@code Class} objects representing the public 1384 * members of this class 1385 * 1386 * @since JDK1.1 1387 */ 1388 @CallerSensitive getClasses()1389 public Class<?>[] getClasses() { 1390 List<Class<?>> result = new ArrayList<Class<?>>(); 1391 for (Class<?> c = this; c != null; c = c.superClass) { 1392 for (Class<?> member : c.getDeclaredClasses()) { 1393 if (Modifier.isPublic(member.getModifiers())) { 1394 result.add(member); 1395 } 1396 } 1397 } 1398 return result.toArray(new Class[result.size()]); 1399 } 1400 1401 1402 /** 1403 * Returns an array containing {@code Field} objects reflecting all 1404 * the accessible public fields of the class or interface represented by 1405 * this {@code Class} object. 1406 * 1407 * <p> If this {@code Class} object represents a class or interface with no 1408 * no accessible public fields, then this method returns an array of length 1409 * 0. 1410 * 1411 * <p> If this {@code Class} object represents a class, then this method 1412 * returns the public fields of the class and of all its superclasses. 1413 * 1414 * <p> If this {@code Class} object represents an interface, then this 1415 * method returns the fields of the interface and of all its 1416 * superinterfaces. 1417 * 1418 * <p> If this {@code Class} object represents an array type, a primitive 1419 * type, or void, then this method returns an array of length 0. 1420 * 1421 * <p> The elements in the returned array are not sorted and are not in any 1422 * particular order. 1423 * 1424 * @return the array of {@code Field} objects representing the 1425 * public fields 1426 * @throws SecurityException 1427 * If a security manager, <i>s</i>, is present and 1428 * the caller's class loader is not the same as or an 1429 * ancestor of the class loader for the current class and 1430 * invocation of {@link SecurityManager#checkPackageAccess 1431 * s.checkPackageAccess()} denies access to the package 1432 * of this class. 1433 * 1434 * @since JDK1.1 1435 * @jls 8.2 Class Members 1436 * @jls 8.3 Field Declarations 1437 */ 1438 @CallerSensitive getFields()1439 public Field[] getFields() throws SecurityException { 1440 List<Field> fields = new ArrayList<Field>(); 1441 getPublicFieldsRecursive(fields); 1442 return fields.toArray(new Field[fields.size()]); 1443 } 1444 1445 /** 1446 * Populates {@code result} with public fields defined by this class, its 1447 * superclasses, and all implemented interfaces. 1448 */ getPublicFieldsRecursive(List<Field> result)1449 private void getPublicFieldsRecursive(List<Field> result) { 1450 // search superclasses 1451 for (Class<?> c = this; c != null; c = c.superClass) { 1452 Collections.addAll(result, c.getPublicDeclaredFields()); 1453 } 1454 1455 // search iftable which has a flattened and uniqued list of interfaces 1456 Object[] iftable = ifTable; 1457 if (iftable != null) { 1458 for (int i = 0; i < iftable.length; i += 2) { 1459 Collections.addAll(result, ((Class<?>) iftable[i]).getPublicDeclaredFields()); 1460 } 1461 } 1462 } 1463 1464 /** 1465 * Returns an array containing {@code Method} objects reflecting all the 1466 * public methods of the class or interface represented by this {@code 1467 * Class} object, including those declared by the class or interface and 1468 * those inherited from superclasses and superinterfaces. 1469 * 1470 * <p> If this {@code Class} object represents a type that has multiple 1471 * public methods with the same name and parameter types, but different 1472 * return types, then the returned array has a {@code Method} object for 1473 * each such method. 1474 * 1475 * <p> If this {@code Class} object represents a type with a class 1476 * initialization method {@code <clinit>}, then the returned array does 1477 * <em>not</em> have a corresponding {@code Method} object. 1478 * 1479 * <p> If this {@code Class} object represents an array type, then the 1480 * returned array has a {@code Method} object for each of the public 1481 * methods inherited by the array type from {@code Object}. It does not 1482 * contain a {@code Method} object for {@code clone()}. 1483 * 1484 * <p> If this {@code Class} object represents an interface then the 1485 * returned array does not contain any implicitly declared methods from 1486 * {@code Object}. Therefore, if no methods are explicitly declared in 1487 * this interface or any of its superinterfaces then the returned array 1488 * has length 0. (Note that a {@code Class} object which represents a class 1489 * always has public methods, inherited from {@code Object}.) 1490 * 1491 * <p> If this {@code Class} object represents a primitive type or void, 1492 * then the returned array has length 0. 1493 * 1494 * <p> Static methods declared in superinterfaces of the class or interface 1495 * represented by this {@code Class} object are not considered members of 1496 * the class or interface. 1497 * 1498 * <p> The elements in the returned array are not sorted and are not in any 1499 * particular order. 1500 * 1501 * @return the array of {@code Method} objects representing the 1502 * public methods of this class 1503 * @throws SecurityException 1504 * If a security manager, <i>s</i>, is present and 1505 * the caller's class loader is not the same as or an 1506 * ancestor of the class loader for the current class and 1507 * invocation of {@link SecurityManager#checkPackageAccess 1508 * s.checkPackageAccess()} denies access to the package 1509 * of this class. 1510 * 1511 * @jls 8.2 Class Members 1512 * @jls 8.4 Method Declarations 1513 * @since JDK1.1 1514 */ 1515 @CallerSensitive getMethods()1516 public Method[] getMethods() throws SecurityException { 1517 List<Method> methods = new ArrayList<Method>(); 1518 getPublicMethodsInternal(methods); 1519 /* 1520 * Remove duplicate methods defined by superclasses and 1521 * interfaces, preferring to keep methods declared by derived 1522 * types. 1523 */ 1524 CollectionUtils.removeDuplicates(methods, Method.ORDER_BY_SIGNATURE); 1525 return methods.toArray(new Method[methods.size()]); 1526 } 1527 1528 /** 1529 * Populates {@code result} with public methods defined by this class, its 1530 * superclasses, and all implemented interfaces, including overridden methods. 1531 */ getPublicMethodsInternal(List<Method> result)1532 private void getPublicMethodsInternal(List<Method> result) { 1533 Collections.addAll(result, getDeclaredMethodsUnchecked(true)); 1534 if (!isInterface()) { 1535 // Search superclasses, for interfaces don't search java.lang.Object. 1536 for (Class<?> c = superClass; c != null; c = c.superClass) { 1537 Collections.addAll(result, c.getDeclaredMethodsUnchecked(true)); 1538 } 1539 } 1540 // Search iftable which has a flattened and uniqued list of interfaces. 1541 Object[] iftable = ifTable; 1542 if (iftable != null) { 1543 for (int i = 0; i < iftable.length; i += 2) { 1544 Class<?> ifc = (Class<?>) iftable[i]; 1545 Collections.addAll(result, ifc.getDeclaredMethodsUnchecked(true)); 1546 } 1547 } 1548 } 1549 1550 /** 1551 * Returns an array containing {@code Constructor} objects reflecting 1552 * all the public constructors of the class represented by this 1553 * {@code Class} object. An array of length 0 is returned if the 1554 * class has no public constructors, or if the class is an array class, or 1555 * if the class reflects a primitive type or void. 1556 * 1557 * Note that while this method returns an array of {@code 1558 * Constructor<T>} objects (that is an array of constructors from 1559 * this class), the return type of this method is {@code 1560 * Constructor<?>[]} and <em>not</em> {@code Constructor<T>[]} as 1561 * might be expected. This less informative return type is 1562 * necessary since after being returned from this method, the 1563 * array could be modified to hold {@code Constructor} objects for 1564 * different classes, which would violate the type guarantees of 1565 * {@code Constructor<T>[]}. 1566 * 1567 * @return the array of {@code Constructor} objects representing the 1568 * public constructors of this class 1569 * @throws SecurityException 1570 * If a security manager, <i>s</i>, is present and 1571 * the caller's class loader is not the same as or an 1572 * ancestor of the class loader for the current class and 1573 * invocation of {@link SecurityManager#checkPackageAccess 1574 * s.checkPackageAccess()} denies access to the package 1575 * of this class. 1576 * 1577 * @since JDK1.1 1578 */ 1579 @CallerSensitive getConstructors()1580 public Constructor<?>[] getConstructors() throws SecurityException { 1581 return getDeclaredConstructorsInternal(true); 1582 } 1583 1584 1585 /** 1586 * Returns a {@code Field} object that reflects the specified public member 1587 * field of the class or interface represented by this {@code Class} 1588 * object. The {@code name} parameter is a {@code String} specifying the 1589 * simple name of the desired field. 1590 * 1591 * <p> The field to be reflected is determined by the algorithm that 1592 * follows. Let C be the class or interface represented by this object: 1593 * 1594 * <OL> 1595 * <LI> If C declares a public field with the name specified, that is the 1596 * field to be reflected.</LI> 1597 * <LI> If no field was found in step 1 above, this algorithm is applied 1598 * recursively to each direct superinterface of C. The direct 1599 * superinterfaces are searched in the order they were declared.</LI> 1600 * <LI> If no field was found in steps 1 and 2 above, and C has a 1601 * superclass S, then this algorithm is invoked recursively upon S. 1602 * If C has no superclass, then a {@code NoSuchFieldException} 1603 * is thrown.</LI> 1604 * </OL> 1605 * 1606 * <p> If this {@code Class} object represents an array type, then this 1607 * method does not find the {@code length} field of the array type. 1608 * 1609 * @param name the field name 1610 * @return the {@code Field} object of this class specified by 1611 * {@code name} 1612 * @throws NoSuchFieldException if a field with the specified name is 1613 * not found. 1614 * @throws NullPointerException if {@code name} is {@code null} 1615 * @throws SecurityException 1616 * If a security manager, <i>s</i>, is present and 1617 * the caller's class loader is not the same as or an 1618 * ancestor of the class loader for the current class and 1619 * invocation of {@link SecurityManager#checkPackageAccess 1620 * s.checkPackageAccess()} denies access to the package 1621 * of this class. 1622 * 1623 * @since JDK1.1 1624 * @jls 8.2 Class Members 1625 * @jls 8.3 Field Declarations 1626 */ 1627 // Android-changed: Removed SecurityException. getField(String name)1628 public Field getField(String name) 1629 throws NoSuchFieldException { 1630 if (name == null) { 1631 throw new NullPointerException("name == null"); 1632 } 1633 Field result = getPublicFieldRecursive(name); 1634 if (result == null) { 1635 throw new NoSuchFieldException(name); 1636 } 1637 return result; 1638 } 1639 1640 /** 1641 * The native implementation of the {@code getField} method. 1642 * 1643 * @throws NullPointerException 1644 * if name is null. 1645 * @see #getField(String) 1646 */ 1647 @FastNative getPublicFieldRecursive(String name)1648 private native Field getPublicFieldRecursive(String name); 1649 1650 /** 1651 * Returns a {@code Method} object that reflects the specified public 1652 * member method of the class or interface represented by this 1653 * {@code Class} object. The {@code name} parameter is a 1654 * {@code String} specifying the simple name of the desired method. The 1655 * {@code parameterTypes} parameter is an array of {@code Class} 1656 * objects that identify the method's formal parameter types, in declared 1657 * order. If {@code parameterTypes} is {@code null}, it is 1658 * treated as if it were an empty array. 1659 * 1660 * <p> If the {@code name} is "{@code <init>}" or "{@code <clinit>}" a 1661 * {@code NoSuchMethodException} is raised. Otherwise, the method to 1662 * be reflected is determined by the algorithm that follows. Let C be the 1663 * class or interface represented by this object: 1664 * <OL> 1665 * <LI> C is searched for a <I>matching method</I>, as defined below. If a 1666 * matching method is found, it is reflected.</LI> 1667 * <LI> If no matching method is found by step 1 then: 1668 * <OL TYPE="a"> 1669 * <LI> If C is a class other than {@code Object}, then this algorithm is 1670 * invoked recursively on the superclass of C.</LI> 1671 * <LI> If C is the class {@code Object}, or if C is an interface, then 1672 * the superinterfaces of C (if any) are searched for a matching 1673 * method. If any such method is found, it is reflected.</LI> 1674 * </OL></LI> 1675 * </OL> 1676 * 1677 * <p> To find a matching method in a class or interface C: If C 1678 * declares exactly one public method with the specified name and exactly 1679 * the same formal parameter types, that is the method reflected. If more 1680 * than one such method is found in C, and one of these methods has a 1681 * return type that is more specific than any of the others, that method is 1682 * reflected; otherwise one of the methods is chosen arbitrarily. 1683 * 1684 * <p>Note that there may be more than one matching method in a 1685 * class because while the Java language forbids a class to 1686 * declare multiple methods with the same signature but different 1687 * return types, the Java virtual machine does not. This 1688 * increased flexibility in the virtual machine can be used to 1689 * implement various language features. For example, covariant 1690 * returns can be implemented with {@linkplain 1691 * java.lang.reflect.Method#isBridge bridge methods}; the bridge 1692 * method and the method being overridden would have the same 1693 * signature but different return types. 1694 * 1695 * <p> If this {@code Class} object represents an array type, then this 1696 * method does not find the {@code clone()} method. 1697 * 1698 * <p> Static methods declared in superinterfaces of the class or interface 1699 * represented by this {@code Class} object are not considered members of 1700 * the class or interface. 1701 * 1702 * @param name the name of the method 1703 * @param parameterTypes the list of parameters 1704 * @return the {@code Method} object that matches the specified 1705 * {@code name} and {@code parameterTypes} 1706 * @throws NoSuchMethodException if a matching method is not found 1707 * or if the name is "<init>"or "<clinit>". 1708 * @throws NullPointerException if {@code name} is {@code null} 1709 * @throws SecurityException 1710 * If a security manager, <i>s</i>, is present and 1711 * the caller's class loader is not the same as or an 1712 * ancestor of the class loader for the current class and 1713 * invocation of {@link SecurityManager#checkPackageAccess 1714 * s.checkPackageAccess()} denies access to the package 1715 * of this class. 1716 * 1717 * @jls 8.2 Class Members 1718 * @jls 8.4 Method Declarations 1719 * @since JDK1.1 1720 */ 1721 @CallerSensitive getMethod(String name, Class<?>... parameterTypes)1722 public Method getMethod(String name, Class<?>... parameterTypes) 1723 throws NoSuchMethodException, SecurityException { 1724 return getMethod(name, parameterTypes, true); 1725 } 1726 1727 1728 /** 1729 * Returns a {@code Constructor} object that reflects the specified 1730 * public constructor of the class represented by this {@code Class} 1731 * object. The {@code parameterTypes} parameter is an array of 1732 * {@code Class} objects that identify the constructor's formal 1733 * parameter types, in declared order. 1734 * 1735 * If this {@code Class} object represents an inner class 1736 * declared in a non-static context, the formal parameter types 1737 * include the explicit enclosing instance as the first parameter. 1738 * 1739 * <p> The constructor to reflect is the public constructor of the class 1740 * represented by this {@code Class} object whose formal parameter 1741 * types match those specified by {@code parameterTypes}. 1742 * 1743 * @param parameterTypes the parameter array 1744 * @return the {@code Constructor} object of the public constructor that 1745 * matches the specified {@code parameterTypes} 1746 * @throws NoSuchMethodException if a matching method is not found. 1747 * @throws SecurityException 1748 * If a security manager, <i>s</i>, is present and 1749 * the caller's class loader is not the same as or an 1750 * ancestor of the class loader for the current class and 1751 * invocation of {@link SecurityManager#checkPackageAccess 1752 * s.checkPackageAccess()} denies access to the package 1753 * of this class. 1754 * 1755 * @since JDK1.1 1756 */ getConstructor(Class<?>.... parameterTypes)1757 public Constructor<T> getConstructor(Class<?>... parameterTypes) 1758 throws NoSuchMethodException, SecurityException { 1759 return getConstructor0(parameterTypes, Member.PUBLIC); 1760 } 1761 1762 1763 /** 1764 * Returns an array of {@code Class} objects reflecting all the 1765 * classes and interfaces declared as members of the class represented by 1766 * this {@code Class} object. This includes public, protected, default 1767 * (package) access, and private classes and interfaces declared by the 1768 * class, but excludes inherited classes and interfaces. This method 1769 * returns an array of length 0 if the class declares no classes or 1770 * interfaces as members, or if this {@code Class} object represents a 1771 * primitive type, an array class, or void. 1772 * 1773 * @return the array of {@code Class} objects representing all the 1774 * declared members of this class 1775 * @throws SecurityException 1776 * If a security manager, <i>s</i>, is present and any of the 1777 * following conditions is met: 1778 * 1779 * <ul> 1780 * 1781 * <li> the caller's class loader is not the same as the 1782 * class loader of this class and invocation of 1783 * {@link SecurityManager#checkPermission 1784 * s.checkPermission} method with 1785 * {@code RuntimePermission("accessDeclaredMembers")} 1786 * denies access to the declared classes within this class 1787 * 1788 * <li> the caller's class loader is not the same as or an 1789 * ancestor of the class loader for the current class and 1790 * invocation of {@link SecurityManager#checkPackageAccess 1791 * s.checkPackageAccess()} denies access to the package 1792 * of this class 1793 * 1794 * </ul> 1795 * 1796 * @since JDK1.1 1797 */ 1798 // Android-changed: Removed SecurityException. 1799 @FastNative getDeclaredClasses()1800 public native Class<?>[] getDeclaredClasses(); 1801 1802 /** 1803 * Returns an array of {@code Field} objects reflecting all the fields 1804 * declared by the class or interface represented by this 1805 * {@code Class} object. This includes public, protected, default 1806 * (package) access, and private fields, but excludes inherited fields. 1807 * 1808 * <p> If this {@code Class} object represents a class or interface with no 1809 * declared fields, then this method returns an array of length 0. 1810 * 1811 * <p> If this {@code Class} object represents an array type, a primitive 1812 * type, or void, then this method returns an array of length 0. 1813 * 1814 * <p> The elements in the returned array are not sorted and are not in any 1815 * particular order. 1816 * 1817 * @return the array of {@code Field} objects representing all the 1818 * declared fields of this class 1819 * @throws SecurityException 1820 * If a security manager, <i>s</i>, is present and any of the 1821 * following conditions is met: 1822 * 1823 * <ul> 1824 * 1825 * <li> the caller's class loader is not the same as the 1826 * class loader of this class and invocation of 1827 * {@link SecurityManager#checkPermission 1828 * s.checkPermission} method with 1829 * {@code RuntimePermission("accessDeclaredMembers")} 1830 * denies access to the declared fields within this class 1831 * 1832 * <li> the caller's class loader is not the same as or an 1833 * ancestor of the class loader for the current class and 1834 * invocation of {@link SecurityManager#checkPackageAccess 1835 * s.checkPackageAccess()} denies access to the package 1836 * of this class 1837 * 1838 * </ul> 1839 * 1840 * @since JDK1.1 1841 * @jls 8.2 Class Members 1842 * @jls 8.3 Field Declarations 1843 */ 1844 // Android-changed: Removed SecurityException. 1845 @FastNative getDeclaredFields()1846 public native Field[] getDeclaredFields(); 1847 1848 /** 1849 * Populates a list of fields without performing any security or type 1850 * resolution checks first. If no fields exist, the list is not modified. 1851 * 1852 * @param publicOnly Whether to return only public fields. 1853 * @hide 1854 */ 1855 @FastNative getDeclaredFieldsUnchecked(boolean publicOnly)1856 public native Field[] getDeclaredFieldsUnchecked(boolean publicOnly); 1857 1858 /** 1859 * 1860 * Returns an array containing {@code Method} objects reflecting all the 1861 * declared methods of the class or interface represented by this {@code 1862 * Class} object, including public, protected, default (package) 1863 * access, and private methods, but excluding inherited methods. 1864 * 1865 * <p> If this {@code Class} object represents a type that has multiple 1866 * declared methods with the same name and parameter types, but different 1867 * return types, then the returned array has a {@code Method} object for 1868 * each such method. 1869 * 1870 * <p> If this {@code Class} object represents a type that has a class 1871 * initialization method {@code <clinit>}, then the returned array does 1872 * <em>not</em> have a corresponding {@code Method} object. 1873 * 1874 * <p> If this {@code Class} object represents a class or interface with no 1875 * declared methods, then the returned array has length 0. 1876 * 1877 * <p> If this {@code Class} object represents an array type, a primitive 1878 * type, or void, then the returned array has length 0. 1879 * 1880 * <p> The elements in the returned array are not sorted and are not in any 1881 * particular order. 1882 * 1883 * @return the array of {@code Method} objects representing all the 1884 * declared methods of this class 1885 * @throws SecurityException 1886 * If a security manager, <i>s</i>, is present and any of the 1887 * following conditions is met: 1888 * 1889 * <ul> 1890 * 1891 * <li> the caller's class loader is not the same as the 1892 * class loader of this class and invocation of 1893 * {@link SecurityManager#checkPermission 1894 * s.checkPermission} method with 1895 * {@code RuntimePermission("accessDeclaredMembers")} 1896 * denies access to the declared methods within this class 1897 * 1898 * <li> the caller's class loader is not the same as or an 1899 * ancestor of the class loader for the current class and 1900 * invocation of {@link SecurityManager#checkPackageAccess 1901 * s.checkPackageAccess()} denies access to the package 1902 * of this class 1903 * 1904 * </ul> 1905 * 1906 * @jls 8.2 Class Members 1907 * @jls 8.4 Method Declarations 1908 * @since JDK1.1 1909 */ getDeclaredMethods()1910 public Method[] getDeclaredMethods() throws SecurityException { 1911 Method[] result = getDeclaredMethodsUnchecked(false); 1912 for (Method m : result) { 1913 // Throw NoClassDefFoundError if types cannot be resolved. 1914 m.getReturnType(); 1915 m.getParameterTypes(); 1916 } 1917 return result; 1918 } 1919 1920 /** 1921 * Populates a list of methods without performing any security or type 1922 * resolution checks first. If no methods exist, the list is not modified. 1923 * 1924 * @param publicOnly Whether to return only public methods. 1925 * @hide 1926 */ 1927 @FastNative getDeclaredMethodsUnchecked(boolean publicOnly)1928 public native Method[] getDeclaredMethodsUnchecked(boolean publicOnly); 1929 1930 /** 1931 * Returns an array of {@code Constructor} objects reflecting all the 1932 * constructors declared by the class represented by this 1933 * {@code Class} object. These are public, protected, default 1934 * (package) access, and private constructors. The elements in the array 1935 * returned are not sorted and are not in any particular order. If the 1936 * class has a default constructor, it is included in the returned array. 1937 * This method returns an array of length 0 if this {@code Class} 1938 * object represents an interface, a primitive type, an array class, or 1939 * void. 1940 * 1941 * <p> See <em>The Java Language Specification</em>, section 8.2. 1942 * 1943 * @return the array of {@code Constructor} objects representing all the 1944 * declared constructors of this class 1945 * @throws SecurityException 1946 * If a security manager, <i>s</i>, is present and any of the 1947 * following conditions is met: 1948 * 1949 * <ul> 1950 * 1951 * <li> the caller's class loader is not the same as the 1952 * class loader of this class and invocation of 1953 * {@link SecurityManager#checkPermission 1954 * s.checkPermission} method with 1955 * {@code RuntimePermission("accessDeclaredMembers")} 1956 * denies access to the declared constructors within this class 1957 * 1958 * <li> the caller's class loader is not the same as or an 1959 * ancestor of the class loader for the current class and 1960 * invocation of {@link SecurityManager#checkPackageAccess 1961 * s.checkPackageAccess()} denies access to the package 1962 * of this class 1963 * 1964 * </ul> 1965 * 1966 * @since JDK1.1 1967 */ getDeclaredConstructors()1968 public Constructor<?>[] getDeclaredConstructors() throws SecurityException { 1969 return getDeclaredConstructorsInternal(false); 1970 } 1971 1972 1973 /** 1974 * Returns the constructor with the given parameters if it is defined by this class; 1975 * {@code null} otherwise. This may return a non-public member. 1976 */ 1977 @FastNative getDeclaredConstructorsInternal(boolean publicOnly)1978 private native Constructor<?>[] getDeclaredConstructorsInternal(boolean publicOnly); 1979 1980 /** 1981 * Returns a {@code Field} object that reflects the specified declared 1982 * field of the class or interface represented by this {@code Class} 1983 * object. The {@code name} parameter is a {@code String} that specifies 1984 * the simple name of the desired field. 1985 * 1986 * <p> If this {@code Class} object represents an array type, then this 1987 * method does not find the {@code length} field of the array type. 1988 * 1989 * @param name the name of the field 1990 * @return the {@code Field} object for the specified field in this 1991 * class 1992 * @throws NoSuchFieldException if a field with the specified name is 1993 * not found. 1994 * @throws NullPointerException if {@code name} is {@code null} 1995 * @throws SecurityException 1996 * If a security manager, <i>s</i>, is present and any of the 1997 * following conditions is met: 1998 * 1999 * <ul> 2000 * 2001 * <li> the caller's class loader is not the same as the 2002 * class loader of this class and invocation of 2003 * {@link SecurityManager#checkPermission 2004 * s.checkPermission} method with 2005 * {@code RuntimePermission("accessDeclaredMembers")} 2006 * denies access to the declared field 2007 * 2008 * <li> the caller's class loader is not the same as or an 2009 * ancestor of the class loader for the current class and 2010 * invocation of {@link SecurityManager#checkPackageAccess 2011 * s.checkPackageAccess()} denies access to the package 2012 * of this class 2013 * 2014 * </ul> 2015 * 2016 * @since JDK1.1 2017 * @jls 8.2 Class Members 2018 * @jls 8.3 Field Declarations 2019 */ 2020 // Android-changed: Removed SecurityException. 2021 @FastNative getDeclaredField(String name)2022 public native Field getDeclaredField(String name) throws NoSuchFieldException; 2023 2024 /** 2025 * Returns the subset of getDeclaredFields which are public. 2026 */ 2027 @FastNative getPublicDeclaredFields()2028 private native Field[] getPublicDeclaredFields(); 2029 2030 /** 2031 * Returns a {@code Method} object that reflects the specified 2032 * declared method of the class or interface represented by this 2033 * {@code Class} object. The {@code name} parameter is a 2034 * {@code String} that specifies the simple name of the desired 2035 * method, and the {@code parameterTypes} parameter is an array of 2036 * {@code Class} objects that identify the method's formal parameter 2037 * types, in declared order. If more than one method with the same 2038 * parameter types is declared in a class, and one of these methods has a 2039 * return type that is more specific than any of the others, that method is 2040 * returned; otherwise one of the methods is chosen arbitrarily. If the 2041 * name is "<init>"or "<clinit>" a {@code NoSuchMethodException} 2042 * is raised. 2043 * 2044 * <p> If this {@code Class} object represents an array type, then this 2045 * method does not find the {@code clone()} method. 2046 * 2047 * @param name the name of the method 2048 * @param parameterTypes the parameter array 2049 * @return the {@code Method} object for the method of this class 2050 * matching the specified name and parameters 2051 * @throws NoSuchMethodException if a matching method is not found. 2052 * @throws NullPointerException if {@code name} is {@code null} 2053 * @throws SecurityException 2054 * If a security manager, <i>s</i>, is present and any of the 2055 * following conditions is met: 2056 * 2057 * <ul> 2058 * 2059 * <li> the caller's class loader is not the same as the 2060 * class loader of this class and invocation of 2061 * {@link SecurityManager#checkPermission 2062 * s.checkPermission} method with 2063 * {@code RuntimePermission("accessDeclaredMembers")} 2064 * denies access to the declared method 2065 * 2066 * <li> the caller's class loader is not the same as or an 2067 * ancestor of the class loader for the current class and 2068 * invocation of {@link SecurityManager#checkPackageAccess 2069 * s.checkPackageAccess()} denies access to the package 2070 * of this class 2071 * 2072 * </ul> 2073 * 2074 * @jls 8.2 Class Members 2075 * @jls 8.4 Method Declarations 2076 * @since JDK1.1 2077 */ 2078 @CallerSensitive getDeclaredMethod(String name, Class<?>... parameterTypes)2079 public Method getDeclaredMethod(String name, Class<?>... parameterTypes) 2080 throws NoSuchMethodException, SecurityException { 2081 return getMethod(name, parameterTypes, false); 2082 } 2083 getMethod(String name, Class<?>[] parameterTypes, boolean recursivePublicMethods)2084 private Method getMethod(String name, Class<?>[] parameterTypes, boolean recursivePublicMethods) 2085 throws NoSuchMethodException { 2086 if (name == null) { 2087 throw new NullPointerException("name == null"); 2088 } 2089 if (parameterTypes == null) { 2090 parameterTypes = EmptyArray.CLASS; 2091 } 2092 for (Class<?> c : parameterTypes) { 2093 if (c == null) { 2094 throw new NoSuchMethodException("parameter type is null"); 2095 } 2096 } 2097 Method result = recursivePublicMethods ? getPublicMethodRecursive(name, parameterTypes) 2098 : getDeclaredMethodInternal(name, parameterTypes); 2099 // Fail if we didn't find the method or it was expected to be public. 2100 if (result == null || 2101 (recursivePublicMethods && !Modifier.isPublic(result.getAccessFlags()))) { 2102 throw new NoSuchMethodException(getName() + "." + name + " " 2103 + Arrays.toString(parameterTypes)); 2104 } 2105 return result; 2106 } getPublicMethodRecursive(String name, Class<?>[] parameterTypes)2107 private Method getPublicMethodRecursive(String name, Class<?>[] parameterTypes) { 2108 // search superclasses 2109 for (Class<?> c = this; c != null; c = c.getSuperclass()) { 2110 Method result = c.getDeclaredMethodInternal(name, parameterTypes); 2111 if (result != null && Modifier.isPublic(result.getAccessFlags())) { 2112 return result; 2113 } 2114 } 2115 2116 return findInterfaceMethod(name, parameterTypes); 2117 } 2118 2119 /** 2120 * Returns an instance method that's defined on this class or any super classes, regardless 2121 * of its access flags. Constructors are excluded. 2122 * 2123 * This function does not perform access checks and its semantics don't match any dex byte code 2124 * instruction or public reflection API. This is used by {@code MethodHandles.findVirtual} 2125 * which will perform access checks on the returned method. 2126 * 2127 * @hide 2128 */ getInstanceMethod(String name, Class<?>[] parameterTypes)2129 public Method getInstanceMethod(String name, Class<?>[] parameterTypes) 2130 throws NoSuchMethodException, IllegalAccessException { 2131 for (Class<?> c = this; c != null; c = c.getSuperclass()) { 2132 Method result = c.getDeclaredMethodInternal(name, parameterTypes); 2133 if (result != null && !Modifier.isStatic(result.getModifiers())) { 2134 return result; 2135 } 2136 } 2137 2138 return findInterfaceMethod(name, parameterTypes); 2139 } 2140 findInterfaceMethod(String name, Class<?>[] parameterTypes)2141 private Method findInterfaceMethod(String name, Class<?>[] parameterTypes) { 2142 Object[] iftable = ifTable; 2143 if (iftable != null) { 2144 // Search backwards so more specific interfaces are searched first. This ensures that 2145 // the method we return is not overridden by one of it's subtypes that this class also 2146 // implements. 2147 for (int i = iftable.length - 2; i >= 0; i -= 2) { 2148 Class<?> ifc = (Class<?>) iftable[i]; 2149 Method result = ifc.getPublicMethodRecursive(name, parameterTypes); 2150 if (result != null && Modifier.isPublic(result.getAccessFlags())) { 2151 return result; 2152 } 2153 } 2154 } 2155 2156 return null; 2157 } 2158 2159 2160 /** 2161 * Returns a {@code Constructor} object that reflects the specified 2162 * constructor of the class or interface represented by this 2163 * {@code Class} object. The {@code parameterTypes} parameter is 2164 * an array of {@code Class} objects that identify the constructor's 2165 * formal parameter types, in declared order. 2166 * 2167 * If this {@code Class} object represents an inner class 2168 * declared in a non-static context, the formal parameter types 2169 * include the explicit enclosing instance as the first parameter. 2170 * 2171 * @param parameterTypes the parameter array 2172 * @return The {@code Constructor} object for the constructor with the 2173 * specified parameter list 2174 * @throws NoSuchMethodException if a matching method is not found. 2175 * @throws SecurityException 2176 * If a security manager, <i>s</i>, is present and any of the 2177 * following conditions is met: 2178 * 2179 * <ul> 2180 * 2181 * <li> the caller's class loader is not the same as the 2182 * class loader of this class and invocation of 2183 * {@link SecurityManager#checkPermission 2184 * s.checkPermission} method with 2185 * {@code RuntimePermission("accessDeclaredMembers")} 2186 * denies access to the declared constructor 2187 * 2188 * <li> the caller's class loader is not the same as or an 2189 * ancestor of the class loader for the current class and 2190 * invocation of {@link SecurityManager#checkPackageAccess 2191 * s.checkPackageAccess()} denies access to the package 2192 * of this class 2193 * 2194 * </ul> 2195 * 2196 * @since JDK1.1 2197 */ 2198 @CallerSensitive getDeclaredConstructor(Class<?>.... parameterTypes)2199 public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes) 2200 throws NoSuchMethodException, SecurityException { 2201 return getConstructor0(parameterTypes, Member.DECLARED); 2202 } 2203 2204 /** 2205 * Finds a resource with a given name. The rules for searching resources 2206 * associated with a given class are implemented by the defining 2207 * {@linkplain ClassLoader class loader} of the class. This method 2208 * delegates to this object's class loader. If this object was loaded by 2209 * the bootstrap class loader, the method delegates to {@link 2210 * ClassLoader#getSystemResourceAsStream}. 2211 * 2212 * <p> Before delegation, an absolute resource name is constructed from the 2213 * given resource name using this algorithm: 2214 * 2215 * <ul> 2216 * 2217 * <li> If the {@code name} begins with a {@code '/'} 2218 * (<tt>'\u002f'</tt>), then the absolute name of the resource is the 2219 * portion of the {@code name} following the {@code '/'}. 2220 * 2221 * <li> Otherwise, the absolute name is of the following form: 2222 * 2223 * <blockquote> 2224 * {@code modified_package_name/name} 2225 * </blockquote> 2226 * 2227 * <p> Where the {@code modified_package_name} is the package name of this 2228 * object with {@code '/'} substituted for {@code '.'} 2229 * (<tt>'\u002e'</tt>). 2230 * 2231 * </ul> 2232 * 2233 * @param name name of the desired resource 2234 * @return A {@link java.io.InputStream} object or {@code null} if 2235 * no resource with this name is found 2236 * @throws NullPointerException If {@code name} is {@code null} 2237 * @since JDK1.1 2238 */ getResourceAsStream(String name)2239 public InputStream getResourceAsStream(String name) { 2240 name = resolveName(name); 2241 ClassLoader cl = getClassLoader(); 2242 if (cl==null) { 2243 // A system class. 2244 return ClassLoader.getSystemResourceAsStream(name); 2245 } 2246 return cl.getResourceAsStream(name); 2247 } 2248 2249 /** 2250 * Finds a resource with a given name. The rules for searching resources 2251 * associated with a given class are implemented by the defining 2252 * {@linkplain ClassLoader class loader} of the class. This method 2253 * delegates to this object's class loader. If this object was loaded by 2254 * the bootstrap class loader, the method delegates to {@link 2255 * ClassLoader#getSystemResource}. 2256 * 2257 * <p> Before delegation, an absolute resource name is constructed from the 2258 * given resource name using this algorithm: 2259 * 2260 * <ul> 2261 * 2262 * <li> If the {@code name} begins with a {@code '/'} 2263 * (<tt>'\u002f'</tt>), then the absolute name of the resource is the 2264 * portion of the {@code name} following the {@code '/'}. 2265 * 2266 * <li> Otherwise, the absolute name is of the following form: 2267 * 2268 * <blockquote> 2269 * {@code modified_package_name/name} 2270 * </blockquote> 2271 * 2272 * <p> Where the {@code modified_package_name} is the package name of this 2273 * object with {@code '/'} substituted for {@code '.'} 2274 * (<tt>'\u002e'</tt>). 2275 * 2276 * </ul> 2277 * 2278 * @param name name of the desired resource 2279 * @return A {@link java.net.URL} object or {@code null} if no 2280 * resource with this name is found 2281 * @since JDK1.1 2282 */ getResource(String name)2283 public java.net.URL getResource(String name) { 2284 name = resolveName(name); 2285 ClassLoader cl = getClassLoader(); 2286 if (cl==null) { 2287 // A system class. 2288 return ClassLoader.getSystemResource(name); 2289 } 2290 return cl.getResource(name); 2291 } 2292 2293 /** 2294 * Returns the {@code ProtectionDomain} of this class. If there is a 2295 * security manager installed, this method first calls the security 2296 * manager's {@code checkPermission} method with a 2297 * {@code RuntimePermission("getProtectionDomain")} permission to 2298 * ensure it's ok to get the 2299 * {@code ProtectionDomain}. 2300 * 2301 * @return the ProtectionDomain of this class 2302 * 2303 * @throws SecurityException 2304 * if a security manager exists and its 2305 * {@code checkPermission} method doesn't allow 2306 * getting the ProtectionDomain. 2307 * 2308 * @see java.security.ProtectionDomain 2309 * @see SecurityManager#checkPermission 2310 * @see java.lang.RuntimePermission 2311 * @since 1.2 2312 */ getProtectionDomain()2313 public java.security.ProtectionDomain getProtectionDomain() { 2314 return null; 2315 } 2316 2317 /* 2318 * Return the runtime's Class object for the named 2319 * primitive type. 2320 */ 2321 @FastNative getPrimitiveClass(String name)2322 static native Class<?> getPrimitiveClass(String name); 2323 2324 /** 2325 * Add a package name prefix if the name is not absolute Remove leading "/" 2326 * if name is absolute 2327 */ resolveName(String name)2328 private String resolveName(String name) { 2329 if (name == null) { 2330 return name; 2331 } 2332 if (!name.startsWith("/")) { 2333 Class<?> c = this; 2334 while (c.isArray()) { 2335 c = c.getComponentType(); 2336 } 2337 String baseName = c.getName(); 2338 int index = baseName.lastIndexOf('.'); 2339 if (index != -1) { 2340 name = baseName.substring(0, index).replace('.', '/') 2341 +"/"+name; 2342 } 2343 } else { 2344 name = name.substring(1); 2345 } 2346 return name; 2347 } 2348 getConstructor0(Class<?>[] parameterTypes, int which)2349 private Constructor<T> getConstructor0(Class<?>[] parameterTypes, 2350 int which) throws NoSuchMethodException 2351 { 2352 if (parameterTypes == null) { 2353 parameterTypes = EmptyArray.CLASS; 2354 } 2355 for (Class<?> c : parameterTypes) { 2356 if (c == null) { 2357 throw new NoSuchMethodException("parameter type is null"); 2358 } 2359 } 2360 Constructor<T> result = getDeclaredConstructorInternal(parameterTypes); 2361 if (result == null || which == Member.PUBLIC && !Modifier.isPublic(result.getAccessFlags())) { 2362 throw new NoSuchMethodException(getName() + ".<init> " 2363 + Arrays.toString(parameterTypes)); 2364 } 2365 return result; 2366 } 2367 2368 /** use serialVersionUID from JDK 1.1 for interoperability */ 2369 private static final long serialVersionUID = 3206093459760846163L; 2370 2371 2372 /** 2373 * Returns the constructor with the given parameters if it is defined by this class; 2374 * {@code null} otherwise. This may return a non-public member. 2375 * 2376 * @param args the types of the parameters to the constructor. 2377 */ 2378 @FastNative getDeclaredConstructorInternal(Class<?>[] args)2379 private native Constructor<T> getDeclaredConstructorInternal(Class<?>[] args); 2380 2381 /** 2382 * Returns the assertion status that would be assigned to this 2383 * class if it were to be initialized at the time this method is invoked. 2384 * If this class has had its assertion status set, the most recent 2385 * setting will be returned; otherwise, if any package default assertion 2386 * status pertains to this class, the most recent setting for the most 2387 * specific pertinent package default assertion status is returned; 2388 * otherwise, if this class is not a system class (i.e., it has a 2389 * class loader) its class loader's default assertion status is returned; 2390 * otherwise, the system class default assertion status is returned. 2391 * <p> 2392 * Few programmers will have any need for this method; it is provided 2393 * for the benefit of the JRE itself. (It allows a class to determine at 2394 * the time that it is initialized whether assertions should be enabled.) 2395 * Note that this method is not guaranteed to return the actual 2396 * assertion status that was (or will be) associated with the specified 2397 * class when it was (or will be) initialized. 2398 * 2399 * Android-note: AssertionStatuses are unsupported. This method will always return false. 2400 * 2401 * @return the desired assertion status of the specified class. 2402 * @see java.lang.ClassLoader#setClassAssertionStatus 2403 * @see java.lang.ClassLoader#setPackageAssertionStatus 2404 * @see java.lang.ClassLoader#setDefaultAssertionStatus 2405 * @since 1.4 2406 */ desiredAssertionStatus()2407 public boolean desiredAssertionStatus() { 2408 return false; 2409 } 2410 2411 /** 2412 * Returns the simple name of a member or local class, or {@code null} otherwise. 2413 */ 2414 @FastNative getInnerClassName()2415 private native String getInnerClassName(); 2416 2417 @FastNative getInnerClassFlags(int defaultValue)2418 private native int getInnerClassFlags(int defaultValue); 2419 2420 /** 2421 * Returns true if and only if this class was declared as an enum in the 2422 * source code. 2423 * 2424 * @return true if and only if this class was declared as an enum in the 2425 * source code 2426 * @since 1.5 2427 */ isEnum()2428 public boolean isEnum() { 2429 // An enum must both directly extend java.lang.Enum and have 2430 // the ENUM bit set; classes for specialized enum constants 2431 // don't do the former. 2432 return (this.getModifiers() & ENUM) != 0 && 2433 this.getSuperclass() == java.lang.Enum.class; 2434 } 2435 2436 /** 2437 * Returns the elements of this enum class or null if this 2438 * Class object does not represent an enum type. 2439 * 2440 * @return an array containing the values comprising the enum class 2441 * represented by this Class object in the order they're 2442 * declared, or null if this Class object does not 2443 * represent an enum type 2444 * @since 1.5 2445 */ getEnumConstants()2446 public T[] getEnumConstants() { 2447 T[] values = getEnumConstantsShared(); 2448 return (values != null) ? values.clone() : null; 2449 } 2450 2451 // Android-changed: Made public/hidden instead of using sun.misc.SharedSecrets. 2452 /** 2453 * Returns the elements of this enum class or null if this 2454 * Class object does not represent an enum type; 2455 * identical to getEnumConstants except that the result is 2456 * uncloned, cached, and shared by all callers. 2457 * @hide 2458 */ getEnumConstantsShared()2459 public T[] getEnumConstantsShared() { 2460 if (!isEnum()) return null; 2461 return (T[]) Enum.getSharedConstants((Class) this); 2462 } 2463 2464 /** 2465 * Casts an object to the class or interface represented 2466 * by this {@code Class} object. 2467 * 2468 * @param obj the object to be cast 2469 * @return the object after casting, or null if obj is null 2470 * 2471 * @throws ClassCastException if the object is not 2472 * null and is not assignable to the type T. 2473 * 2474 * @since 1.5 2475 */ 2476 @SuppressWarnings("unchecked") cast(Object obj)2477 public T cast(Object obj) { 2478 if (obj != null && !isInstance(obj)) 2479 throw new ClassCastException(cannotCastMsg(obj)); 2480 return (T) obj; 2481 } 2482 cannotCastMsg(Object obj)2483 private String cannotCastMsg(Object obj) { 2484 return "Cannot cast " + obj.getClass().getName() + " to " + getName(); 2485 } 2486 2487 /** 2488 * Casts this {@code Class} object to represent a subclass of the class 2489 * represented by the specified class object. Checks that the cast 2490 * is valid, and throws a {@code ClassCastException} if it is not. If 2491 * this method succeeds, it always returns a reference to this class object. 2492 * 2493 * <p>This method is useful when a client needs to "narrow" the type of 2494 * a {@code Class} object to pass it to an API that restricts the 2495 * {@code Class} objects that it is willing to accept. A cast would 2496 * generate a compile-time warning, as the correctness of the cast 2497 * could not be checked at runtime (because generic types are implemented 2498 * by erasure). 2499 * 2500 * @param <U> the type to cast this class object to 2501 * @param clazz the class of the type to cast this class object to 2502 * @return this {@code Class} object, cast to represent a subclass of 2503 * the specified class object. 2504 * @throws ClassCastException if this {@code Class} object does not 2505 * represent a subclass of the specified class (here "subclass" includes 2506 * the class itself). 2507 * @since 1.5 2508 */ 2509 @SuppressWarnings("unchecked") asSubclass(Class<U> clazz)2510 public <U> Class<? extends U> asSubclass(Class<U> clazz) { 2511 if (clazz.isAssignableFrom(this)) 2512 return (Class<? extends U>) this; 2513 else 2514 throw new ClassCastException(this.toString() + 2515 " cannot be cast to " + clazz.getName()); 2516 } 2517 2518 /** 2519 * @throws NullPointerException {@inheritDoc} 2520 * @since 1.5 2521 */ 2522 @SuppressWarnings("unchecked") getAnnotation(Class<A> annotationClass)2523 public <A extends Annotation> A getAnnotation(Class<A> annotationClass) { 2524 Objects.requireNonNull(annotationClass); 2525 2526 A annotation = getDeclaredAnnotation(annotationClass); 2527 if (annotation != null) { 2528 return annotation; 2529 } 2530 2531 if (annotationClass.isDeclaredAnnotationPresent(Inherited.class)) { 2532 for (Class<?> sup = getSuperclass(); sup != null; sup = sup.getSuperclass()) { 2533 annotation = sup.getDeclaredAnnotation(annotationClass); 2534 if (annotation != null) { 2535 return annotation; 2536 } 2537 } 2538 } 2539 2540 return null; 2541 } 2542 2543 /** 2544 * {@inheritDoc} 2545 * @throws NullPointerException {@inheritDoc} 2546 * @since 1.5 2547 */ 2548 @Override isAnnotationPresent(Class<? extends Annotation> annotationClass)2549 public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) { 2550 if (annotationClass == null) { 2551 throw new NullPointerException("annotationClass == null"); 2552 } 2553 2554 if (isDeclaredAnnotationPresent(annotationClass)) { 2555 return true; 2556 } 2557 2558 if (annotationClass.isDeclaredAnnotationPresent(Inherited.class)) { 2559 for (Class<?> sup = getSuperclass(); sup != null; sup = sup.getSuperclass()) { 2560 if (sup.isDeclaredAnnotationPresent(annotationClass)) { 2561 return true; 2562 } 2563 } 2564 } 2565 2566 return false; 2567 } 2568 2569 /** 2570 * @throws NullPointerException {@inheritDoc} 2571 * @since 1.8 2572 */ 2573 @Override getAnnotationsByType(Class<A> annotationClass)2574 public <A extends Annotation> A[] getAnnotationsByType(Class<A> annotationClass) { 2575 // Find any associated annotations [directly or repeatably (indirectly) present on this]. 2576 A[] annotations = GenericDeclaration.super.getAnnotationsByType(annotationClass); 2577 2578 if (annotations.length != 0) { 2579 return annotations; 2580 } 2581 2582 // Nothing was found, attempt looking for associated annotations recursively up to the root 2583 // class if and only if: 2584 // * The annotation class was marked with @Inherited. 2585 // 2586 // Inherited annotations are not coalesced into a single set: the first declaration found is 2587 // returned. 2588 2589 if (annotationClass.isDeclaredAnnotationPresent(Inherited.class)) { 2590 Class<?> superClass = getSuperclass(); // Returns null if klass's base is Object. 2591 2592 if (superClass != null) { 2593 return superClass.getAnnotationsByType(annotationClass); 2594 } 2595 } 2596 2597 // Annotated was not marked with @Inherited, or no superclass. 2598 return (A[]) Array.newInstance(annotationClass, 0); // Safe by construction. 2599 } 2600 2601 /** 2602 * @since 1.5 2603 */ 2604 @Override getAnnotations()2605 public Annotation[] getAnnotations() { 2606 /* 2607 * We need to get the annotations declared on this class, plus the 2608 * annotations from superclasses that have the "@Inherited" annotation 2609 * set. We create a temporary map to use while we accumulate the 2610 * annotations and convert it to an array at the end. 2611 * 2612 * It's possible to have duplicates when annotations are inherited. 2613 * We use a Map to filter those out. 2614 * 2615 * HashMap might be overkill here. 2616 */ 2617 HashMap<Class<?>, Annotation> map = new HashMap<Class<?>, Annotation>(); 2618 for (Annotation declaredAnnotation : getDeclaredAnnotations()) { 2619 map.put(declaredAnnotation.annotationType(), declaredAnnotation); 2620 } 2621 for (Class<?> sup = getSuperclass(); sup != null; sup = sup.getSuperclass()) { 2622 for (Annotation declaredAnnotation : sup.getDeclaredAnnotations()) { 2623 Class<? extends Annotation> clazz = declaredAnnotation.annotationType(); 2624 if (!map.containsKey(clazz) && clazz.isDeclaredAnnotationPresent(Inherited.class)) { 2625 map.put(clazz, declaredAnnotation); 2626 } 2627 } 2628 } 2629 2630 /* Convert annotation values from HashMap to array. */ 2631 Collection<Annotation> coll = map.values(); 2632 return coll.toArray(new Annotation[coll.size()]); 2633 } 2634 2635 /** 2636 * @throws NullPointerException {@inheritDoc} 2637 * @since 1.8 2638 */ 2639 @Override 2640 @FastNative getDeclaredAnnotation(Class<A> annotationClass)2641 public native <A extends Annotation> A getDeclaredAnnotation(Class<A> annotationClass); 2642 2643 /** 2644 * @since 1.5 2645 */ 2646 @Override 2647 @FastNative getDeclaredAnnotations()2648 public native Annotation[] getDeclaredAnnotations(); 2649 2650 /** 2651 * Returns true if the annotation exists. 2652 */ 2653 @FastNative isDeclaredAnnotationPresent(Class<? extends Annotation> annotationClass)2654 private native boolean isDeclaredAnnotationPresent(Class<? extends Annotation> annotationClass); 2655 getSignatureAttribute()2656 private String getSignatureAttribute() { 2657 String[] annotation = getSignatureAnnotation(); 2658 if (annotation == null) { 2659 return null; 2660 } 2661 StringBuilder result = new StringBuilder(); 2662 for (String s : annotation) { 2663 result.append(s); 2664 } 2665 return result.toString(); 2666 } 2667 2668 @FastNative getSignatureAnnotation()2669 private native String[] getSignatureAnnotation(); 2670 2671 /** 2672 * Is this a runtime created proxy class? 2673 * 2674 * @hide 2675 */ isProxy()2676 public boolean isProxy() { 2677 return (accessFlags & 0x00040000) != 0; 2678 } 2679 2680 /** 2681 * @hide 2682 */ getAccessFlags()2683 public int getAccessFlags() { 2684 return accessFlags; 2685 } 2686 2687 2688 /** 2689 * Returns the method if it is defined by this class; {@code null} otherwise. This may return a 2690 * non-public member. 2691 * 2692 * @param name the method name 2693 * @param args the method's parameter types 2694 */ 2695 @FastNative getDeclaredMethodInternal(String name, Class<?>[] args)2696 private native Method getDeclaredMethodInternal(String name, Class<?>[] args); 2697 2698 private static class Caches { 2699 /** 2700 * Cache to avoid frequent recalculation of generic interfaces, which is generally uncommon. 2701 * Sized sufficient to allow ConcurrentHashMapTest to run without recalculating its generic 2702 * interfaces (required to avoid time outs). Validated by running reflection heavy code 2703 * such as applications using Guice-like frameworks. 2704 */ 2705 private static final BasicLruCache<Class, Type[]> genericInterfaces 2706 = new BasicLruCache<Class, Type[]>(8); 2707 } 2708 } 2709