1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one or more 3 * contributor license agreements. See the NOTICE file distributed with 4 * this work for additional information regarding copyright ownership. 5 * The ASF licenses this file to You under the Apache License, Version 2.0 6 * (the "License"); you may not use this file except in compliance with 7 * the License. You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 /* 18 * Copyright (C) 2006-2007 The Android Open Source Project 19 * 20 * Licensed under the Apache License, Version 2.0 (the "License"); 21 * you may not use this file except in compliance with the License. 22 * You may obtain a copy of the License at 23 * 24 * http://www.apache.org/licenses/LICENSE-2.0 25 * 26 * Unless required by applicable law or agreed to in writing, software 27 * distributed under the License is distributed on an "AS IS" BASIS, 28 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 29 * See the License for the specific language governing permissions and 30 * limitations under the License. 31 */ 32 33 package java.lang; 34 35 import com.android.dex.Dex; 36 import dalvik.system.VMStack; 37 import java.io.InputStream; 38 import java.io.Serializable; 39 import java.lang.annotation.Annotation; 40 import java.lang.reflect.AccessibleObject; 41 import java.lang.reflect.AnnotatedElement; 42 import java.lang.reflect.Constructor; 43 import java.lang.reflect.Field; 44 import java.lang.reflect.GenericDeclaration; 45 import java.lang.reflect.InvocationTargetException; 46 import java.lang.reflect.Member; 47 import java.lang.reflect.Method; 48 import java.lang.reflect.Modifier; 49 import java.lang.reflect.Type; 50 import java.lang.reflect.TypeVariable; 51 import java.net.URL; 52 import java.nio.charset.StandardCharsets; 53 import java.security.ProtectionDomain; 54 import java.util.ArrayList; 55 import java.util.Arrays; 56 import java.util.Collections; 57 import java.util.List; 58 import libcore.reflect.AnnotationAccess; 59 import libcore.reflect.GenericSignatureParser; 60 import libcore.reflect.InternalNames; 61 import libcore.reflect.Types; 62 import libcore.util.BasicLruCache; 63 import libcore.util.CollectionUtils; 64 import libcore.util.EmptyArray; 65 import libcore.util.SneakyThrow; 66 67 /** 68 * The in-memory representation of a Java class. This representation serves as 69 * the starting point for querying class-related information, a process usually 70 * called "reflection". There are basically three types of {@code Class} 71 * instances: those representing real classes and interfaces, those representing 72 * primitive types, and those representing array classes. 73 * 74 * <h4>Class instances representing object types (classes or interfaces)</h4> 75 * <p> 76 * These represent an ordinary class or interface as found in the class 77 * hierarchy. The name associated with these {@code Class} instances is simply 78 * the fully qualified class name of the class or interface that it represents. 79 * In addition to this human-readable name, each class is also associated by a 80 * so-called <em>descriptor</em>, which is the letter "L", followed by the 81 * class name and a semicolon (";"). The descriptor is what the runtime system 82 * uses internally for identifying the class (for example in a DEX file). 83 * </p> 84 * <h4>Classes representing primitive types</h4> 85 * <p> 86 * These represent the standard Java primitive types and hence share their 87 * names (for example "int" for the {@code int} primitive type). Although it is 88 * not possible to create new instances based on these {@code Class} instances, 89 * they are still useful for providing reflection information, and as the 90 * component type of array classes. There is one {@code Class} instance for each 91 * primitive type, and their descriptors are: 92 * </p> 93 * <ul> 94 * <li>{@code B} representing the {@code byte} primitive type</li> 95 * <li>{@code S} representing the {@code short} primitive type</li> 96 * <li>{@code I} representing the {@code int} primitive type</li> 97 * <li>{@code J} representing the {@code long} primitive type</li> 98 * <li>{@code F} representing the {@code float} primitive type</li> 99 * <li>{@code D} representing the {@code double} primitive type</li> 100 * <li>{@code C} representing the {@code char} primitive type</li> 101 * <li>{@code Z} representing the {@code boolean} primitive type</li> 102 * <li>{@code V} representing void function return values</li> 103 * </ul> 104 * <p> 105 * <h4>Classes representing array classes</h4> 106 * <p> 107 * These represent the classes of Java arrays. There is one such {@code Class} 108 * instance per combination of array leaf component type and arity (number of 109 * dimensions). In this case, the name associated with the {@code Class} 110 * consists of one or more left square brackets (one per dimension in the array) 111 * followed by the descriptor of the class representing the leaf component type, 112 * which can be either an object type or a primitive type. The descriptor of a 113 * {@code Class} representing an array type is the same as its name. Examples 114 * of array class descriptors are: 115 * </p> 116 * <ul> 117 * <li>{@code [I} representing the {@code int[]} type</li> 118 * <li>{@code [Ljava/lang/String;} representing the {@code String[]} type</li> 119 * <li>{@code [[[C} representing the {@code char[][][]} type (three dimensions!)</li> 120 * </ul> 121 */ 122 public final class Class<T> implements Serializable, AnnotatedElement, GenericDeclaration, Type { 123 124 private static final long serialVersionUID = 3206093459760846163L; 125 126 /** defining class loader, or null for the "bootstrap" system loader. */ 127 private transient ClassLoader classLoader; 128 129 /** 130 * For array classes, the component class object for instanceof/checkcast (for String[][][], 131 * this will be String[][]). null for non-array classes. 132 */ 133 private transient Class<?> componentType; 134 /** 135 * DexCache of resolved constant pool entries. Will be null for certain runtime-generated classes 136 * e.g. arrays and primitive classes. 137 */ 138 private transient DexCache dexCache; 139 140 /** Short-cut to dexCache.strings */ 141 private transient String[] dexCacheStrings; 142 143 /** 144 * The interface table (iftable_) contains pairs of a interface class and an array of the 145 * interface methods. There is one pair per interface supported by this class. That 146 * means one pair for each interface we support directly, indirectly via superclass, or 147 * indirectly via a superinterface. This will be null if neither we nor our superclass 148 * implement any interfaces. 149 * 150 * Why we need this: given "class Foo implements Face", declare "Face faceObj = new Foo()". 151 * Invoke faceObj.blah(), where "blah" is part of the Face interface. We can't easily use a 152 * single vtable. 153 * 154 * For every interface a concrete class implements, we create an array of the concrete vtable_ 155 * methods for the methods in the interface. 156 */ 157 private transient Object[] ifTable; 158 159 /** Lazily computed name of this class; always prefer calling getName(). */ 160 private transient String name; 161 162 /** The superclass, or null if this is java.lang.Object, an interface or primitive type. */ 163 private transient Class<? super T> superClass; 164 165 /** If class verify fails, we must return same error on subsequent tries. */ 166 private transient Class<?> verifyErrorClass; 167 168 /** 169 * Virtual method table (vtable), for use by "invoke-virtual". The vtable from the superclass 170 * is copied in, and virtual methods from our class either replace those from the super or are 171 * appended. For abstract classes, methods may be created in the vtable that aren't in 172 * virtual_ methods_ for miranda methods. 173 */ 174 private transient Object vtable; 175 176 /** access flags; low 16 bits are defined by VM spec */ 177 private transient int accessFlags; 178 179 /** static, private, and <init> methods. */ 180 private transient long directMethods; 181 182 /** 183 * Instance fields. These describe the layout of the contents of an Object. Note that only the 184 * fields directly declared by this class are listed in iFields; fields declared by a 185 * superclass are listed in the superclass's Class.iFields. 186 * 187 * All instance fields that refer to objects are guaranteed to be at the beginning of the field 188 * list. {@link Class#numReferenceInstanceFields} specifies the number of reference fields. 189 */ 190 private transient long iFields; 191 192 /** Static fields */ 193 private transient long sFields; 194 195 /** Virtual methods defined in this class; invoked through vtable. */ 196 private transient long virtualMethods; 197 198 /** 199 * Total size of the Class instance; used when allocating storage on GC heap. 200 * See also {@link Class#objectSize}. 201 */ 202 private transient int classSize; 203 204 /** 205 * tid used to check for recursive static initializer invocation. 206 */ 207 private transient int clinitThreadId; 208 209 /** 210 * Class def index from dex file. An index of 65535 indicates that there is no class definition, 211 * for example for an array type. 212 * TODO: really 16bits as type indices are 16bit. 213 */ 214 private transient int dexClassDefIndex; 215 216 /** 217 * Class type index from dex file, lazily computed. An index of 65535 indicates that the type 218 * index isn't known. Volatile to avoid double-checked locking bugs. 219 * TODO: really 16bits as type indices are 16bit. 220 */ 221 private transient volatile int dexTypeIndex; 222 223 /** Number of direct methods. */ 224 private transient int numDirectMethods; 225 226 /** Number of instance fields. */ 227 private transient int numInstanceFields; 228 229 /** Number of instance fields that are object references. */ 230 private transient int numReferenceInstanceFields; 231 232 /** Number of static fields that are object references. */ 233 private transient int numReferenceStaticFields; 234 235 /** Number of static fields. */ 236 private transient int numStaticFields; 237 238 /** Number of virtual methods. */ 239 private transient int numVirtualMethods; 240 241 /** 242 * Total object size; used when allocating storage on GC heap. For interfaces and abstract 243 * classes this will be zero. See also {@link Class#classSize}. 244 */ 245 private transient int objectSize; 246 247 /** 248 * The lower 16 bits is the primitive type value, or 0 if not a primitive type; set for 249 * generated primitive classes. 250 */ 251 private transient int primitiveType; 252 253 /** Bitmap of offsets of iFields. */ 254 private transient int referenceInstanceOffsets; 255 256 /** State of class initialization */ 257 private transient int status; 258 Class()259 private Class() { 260 // Prevent this class from being instantiated, 261 // instances should be created by the runtime only. 262 } 263 264 /** 265 * Returns a {@code Class} object which represents the class with 266 * the given name. The name should be the name of a non-primitive 267 * class, as described in the {@link Class class definition}. 268 * Primitive types can not be found using this method; use {@code 269 * int.class} or {@code Integer.TYPE} instead. 270 * 271 * <p>If the class has not yet been loaded, it is loaded and initialized 272 * first. This is done through either the class loader of the calling class 273 * or one of its parent class loaders. It is possible that a static initializer is run as 274 * a result of this call. 275 * 276 * @throws ClassNotFoundException 277 * if the requested class cannot be found. 278 * @throws LinkageError 279 * if an error occurs during linkage 280 * @throws ExceptionInInitializerError 281 * if an exception occurs during static initialization of a 282 * class. 283 */ forName(String className)284 public static Class<?> forName(String className) throws ClassNotFoundException { 285 return forName(className, true, VMStack.getCallingClassLoader()); 286 } 287 288 /** 289 * Returns a {@code Class} object which represents the class with 290 * the given name. The name should be the name of a non-primitive 291 * class, as described in the {@link Class class definition}. 292 * Primitive types can not be found using this method; use {@code 293 * int.class} or {@code Integer.TYPE} instead. 294 * 295 * <p>If the class has not yet been loaded, it is loaded first, using the given class loader. 296 * If the class has not yet been initialized and {@code shouldInitialize} is true, 297 * the class will be initialized. 298 * 299 * <p>If the provided {@code classLoader} is {@code null}, the bootstrap 300 * class loader will be used to load the class. 301 * 302 * @throws ClassNotFoundException 303 * if the requested class cannot be found. 304 * @throws LinkageError 305 * if an error occurs during linkage 306 * @throws ExceptionInInitializerError 307 * if an exception occurs during static initialization of a 308 * class. 309 */ forName(String className, boolean shouldInitialize, ClassLoader classLoader)310 public static Class<?> forName(String className, boolean shouldInitialize, 311 ClassLoader classLoader) throws ClassNotFoundException { 312 313 if (classLoader == null) { 314 classLoader = BootClassLoader.getInstance(); 315 } 316 // Catch an Exception thrown by the underlying native code. It wraps 317 // up everything inside a ClassNotFoundException, even if e.g. an 318 // Error occurred during initialization. This as a workaround for 319 // an ExceptionInInitializerError that's also wrapped. It is actually 320 // expected to be thrown. Maybe the same goes for other errors. 321 // Not wrapping up all the errors will break android though. 322 Class<?> result; 323 try { 324 result = classForName(className, shouldInitialize, classLoader); 325 } catch (ClassNotFoundException e) { 326 Throwable cause = e.getCause(); 327 if (cause instanceof LinkageError) { 328 throw (LinkageError) cause; 329 } 330 throw e; 331 } 332 return result; 333 } 334 classForName(String className, boolean shouldInitialize, ClassLoader classLoader)335 static native Class<?> classForName(String className, boolean shouldInitialize, 336 ClassLoader classLoader) throws ClassNotFoundException; 337 338 /** 339 * Returns an array containing {@code Class} objects for all 340 * public classes, interfaces, enums and annotations that are 341 * members of this class and its superclasses. This does not 342 * include classes of implemented interfaces. If there are no 343 * such class members or if this object represents a primitive 344 * type then an array of length 0 is returned. 345 */ getClasses()346 public Class<?>[] getClasses() { 347 List<Class<?>> result = new ArrayList<Class<?>>(); 348 for (Class<?> c = this; c != null; c = c.superClass) { 349 for (Class<?> member : c.getDeclaredClasses()) { 350 if (Modifier.isPublic(member.getModifiers())) { 351 result.add(member); 352 } 353 } 354 } 355 return result.toArray(new Class[result.size()]); 356 } 357 getAnnotation(Class<A> annotationType)358 @Override public <A extends Annotation> A getAnnotation(Class<A> annotationType) { 359 return AnnotationAccess.getAnnotation(this, annotationType); 360 } 361 362 /** 363 * Returns an array containing all the annotations of this class. If there are no annotations 364 * then an empty array is returned. 365 * 366 * @see #getDeclaredAnnotations() 367 */ getAnnotations()368 @Override public Annotation[] getAnnotations() { 369 return AnnotationAccess.getAnnotations(this); 370 } 371 372 /** 373 * Returns the canonical name of this class. If this class does not have a 374 * canonical name as defined in the Java Language Specification, then the 375 * method returns {@code null}. 376 */ getCanonicalName()377 public String getCanonicalName() { 378 if (isLocalClass() || isAnonymousClass()) 379 return null; 380 381 if (isArray()) { 382 /* 383 * The canonical name of an array type depends on the (existence of) 384 * the component type's canonical name. 385 */ 386 String name = getComponentType().getCanonicalName(); 387 if (name != null) { 388 return name + "[]"; 389 } 390 } else if (isMemberClass()) { 391 /* 392 * The canonical name of an inner class depends on the (existence 393 * of) the declaring class' canonical name. 394 */ 395 String name = getDeclaringClass().getCanonicalName(); 396 if (name != null) { 397 return name + "." + getSimpleName(); 398 } 399 } else { 400 /* 401 * The canonical name of a top-level class or primitive type is 402 * equal to the fully qualified name. 403 */ 404 return getName(); 405 } 406 407 /* 408 * Other classes don't have a canonical name. 409 */ 410 return null; 411 } 412 413 /** 414 * Returns the class loader which was used to load the class represented by 415 * this {@code Class}. Implementations are free to return {@code null} for 416 * classes that were loaded by the bootstrap class loader. The Android 417 * reference implementation, though, always returns a reference to an actual 418 * class loader. 419 */ getClassLoader()420 public ClassLoader getClassLoader() { 421 if (this.isPrimitive()) { 422 return null; 423 } 424 425 final ClassLoader loader = classLoader; 426 return loader == null ? BootClassLoader.getInstance() : loader; 427 } 428 429 /** 430 * Returns a {@code Class} object which represents the component type if 431 * this class represents an array type. Returns {@code null} if this class 432 * does not represent an array type. The component type of an array type is 433 * the type of the elements of the array. 434 */ getComponentType()435 public Class<?> getComponentType() { 436 return componentType; 437 } 438 439 /** 440 * Returns the dex file from which this class was loaded. 441 * 442 * @hide 443 */ getDex()444 public Dex getDex() { 445 if (dexCache == null) { 446 return null; 447 } 448 return dexCache.getDex(); 449 } 450 451 /** 452 * Returns a string from the dex cache, computing the string from the dex file if necessary. 453 * 454 * @hide 455 */ getDexCacheString(Dex dex, int dexStringIndex)456 public String getDexCacheString(Dex dex, int dexStringIndex) { 457 String s = dexCache.getResolvedString(dexStringIndex); 458 if (s == null) { 459 s = dex.strings().get(dexStringIndex).intern(); 460 dexCache.setResolvedString(dexStringIndex, s); 461 } 462 return s; 463 } 464 465 /** 466 * Returns a resolved type from the dex cache, computing the type from the dex file if 467 * necessary. 468 * 469 * @hide 470 */ getDexCacheType(Dex dex, int dexTypeIndex)471 public Class<?> getDexCacheType(Dex dex, int dexTypeIndex) { 472 Class<?> resolvedType = dexCache.getResolvedType(dexTypeIndex); 473 if (resolvedType == null) { 474 int descriptorIndex = dex.typeIds().get(dexTypeIndex); 475 String descriptor = getDexCacheString(dex, descriptorIndex); 476 resolvedType = InternalNames.getClass(getClassLoader(), descriptor); 477 dexCache.setResolvedType(dexTypeIndex, resolvedType); 478 } 479 return resolvedType; 480 } 481 482 /** 483 * Returns a {@code Constructor} object which represents the public 484 * constructor matching the given parameter types. 485 * {@code (Class[]) null} is equivalent to the empty array. 486 * 487 * @throws NoSuchMethodException 488 * if the constructor cannot be found. 489 * @see #getDeclaredConstructor(Class[]) 490 */ getConstructor(Class<?>.... parameterTypes)491 public Constructor<T> getConstructor(Class<?>... parameterTypes) throws NoSuchMethodException { 492 return getConstructor(parameterTypes, true); 493 } 494 495 /** 496 * Returns a {@code Constructor} object which represents the constructor 497 * matching the specified parameter types that is declared by the class 498 * represented by this {@code Class}. 499 * {@code (Class[]) null} is equivalent to the empty array. 500 * 501 * @throws NoSuchMethodException 502 * if the requested constructor cannot be found. 503 * @see #getConstructor(Class[]) 504 */ getDeclaredConstructor(Class<?>.... parameterTypes)505 public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes) 506 throws NoSuchMethodException { 507 return getConstructor(parameterTypes, false); 508 } 509 510 /** 511 * Returns a constructor with the given parameters. 512 * 513 * @param publicOnly true to only return public constructores. 514 * @param parameterTypes argument types to match the constructor's. 515 */ getConstructor(Class<?>[] parameterTypes, boolean publicOnly)516 private Constructor<T> getConstructor(Class<?>[] parameterTypes, boolean publicOnly) 517 throws NoSuchMethodException { 518 if (parameterTypes == null) { 519 parameterTypes = EmptyArray.CLASS; 520 } 521 for (Class<?> c : parameterTypes) { 522 if (c == null) { 523 throw new NoSuchMethodException("parameter type is null"); 524 } 525 } 526 Constructor<T> result = getDeclaredConstructorInternal(parameterTypes); 527 if (result == null || publicOnly && !Modifier.isPublic(result.getAccessFlags())) { 528 throw new NoSuchMethodException("<init> " + Arrays.toString(parameterTypes)); 529 } 530 return result; 531 } 532 533 /** 534 * Returns the constructor with the given parameters if it is defined by this class; 535 * {@code null} otherwise. This may return a non-public member. 536 * 537 * @param args the types of the parameters to the constructor. 538 */ getDeclaredConstructorInternal(Class<?>[] args)539 private native Constructor<T> getDeclaredConstructorInternal(Class<?>[] args); 540 541 /** 542 * Returns an array containing {@code Constructor} objects for all public 543 * constructors for this {@code Class}. If there 544 * are no public constructors or if this {@code Class} represents an array 545 * class, a primitive type or void then an empty array is returned. 546 * 547 * @see #getDeclaredConstructors() 548 */ getConstructors()549 public Constructor<?>[] getConstructors() { 550 return getDeclaredConstructorsInternal(true); 551 } 552 553 /** 554 * Returns an array containing {@code Constructor} objects for all 555 * constructors declared in the class represented by this {@code Class}. If 556 * there are no constructors or if this {@code Class} represents an array 557 * class, a primitive type or void then an empty array is returned. 558 * 559 * @see #getConstructors() 560 */ getDeclaredConstructors()561 public Constructor<?>[] getDeclaredConstructors() { 562 return getDeclaredConstructorsInternal(false); 563 } 564 getDeclaredConstructorsInternal(boolean publicOnly)565 private native Constructor<?>[] getDeclaredConstructorsInternal(boolean publicOnly); 566 567 /** 568 * Returns a {@code Method} object which represents the method matching the 569 * specified name and parameter types that is declared by the class 570 * represented by this {@code Class}. 571 * 572 * @param name 573 * the requested method's name. 574 * @param parameterTypes 575 * the parameter types of the requested method. 576 * {@code (Class[]) null} is equivalent to the empty array. 577 * @return the method described by {@code name} and {@code parameterTypes}. 578 * @throws NoSuchMethodException 579 * if the requested constructor cannot be found. 580 * @throws NullPointerException 581 * if {@code name} is {@code null}. 582 * @see #getMethod(String, Class[]) 583 */ getDeclaredMethod(String name, Class<?>... parameterTypes)584 public Method getDeclaredMethod(String name, Class<?>... parameterTypes) 585 throws NoSuchMethodException { 586 return getMethod(name, parameterTypes, false); 587 } 588 589 /** 590 * Returns a {@code Method} object which represents the public method with 591 * the specified name and parameter types. 592 * {@code (Class[]) null} is equivalent to the empty array. 593 * This method first searches the 594 * class C represented by this {@code Class}, then the superclasses of C and 595 * finally the interfaces implemented by C and finally the superclasses of C 596 * for a method with matching name. 597 * 598 * @throws NoSuchMethodException 599 * if the method cannot be found. 600 * @see #getDeclaredMethod(String, Class[]) 601 */ getMethod(String name, Class<?>... parameterTypes)602 public Method getMethod(String name, Class<?>... parameterTypes) throws NoSuchMethodException { 603 return getMethod(name, parameterTypes, true); 604 } 605 getMethod(String name, Class<?>[] parameterTypes, boolean recursivePublicMethods)606 private Method getMethod(String name, Class<?>[] parameterTypes, boolean recursivePublicMethods) 607 throws NoSuchMethodException { 608 if (name == null) { 609 throw new NullPointerException("name == null"); 610 } 611 if (parameterTypes == null) { 612 parameterTypes = EmptyArray.CLASS; 613 } 614 for (Class<?> c : parameterTypes) { 615 if (c == null) { 616 throw new NoSuchMethodException("parameter type is null"); 617 } 618 } 619 Method result = recursivePublicMethods ? getPublicMethodRecursive(name, parameterTypes) 620 : getDeclaredMethodInternal(name, parameterTypes); 621 // Fail if we didn't find the method or it was expected to be public. 622 if (result == null || 623 (recursivePublicMethods && !Modifier.isPublic(result.getAccessFlags()))) { 624 throw new NoSuchMethodException(name + " " + Arrays.toString(parameterTypes)); 625 } 626 return result; 627 } 628 getPublicMethodRecursive(String name, Class<?>[] parameterTypes)629 private Method getPublicMethodRecursive(String name, Class<?>[] parameterTypes) { 630 // search superclasses 631 for (Class<?> c = this; c != null; c = c.getSuperclass()) { 632 Method result = c.getDeclaredMethodInternal(name, parameterTypes); 633 if (result != null && Modifier.isPublic(result.getAccessFlags())) { 634 return result; 635 } 636 } 637 // search iftable which has a flattened and uniqued list of interfaces 638 Object[] iftable = ifTable; 639 if (iftable != null) { 640 for (int i = 0; i < iftable.length; i += 2) { 641 Class<?> ifc = (Class<?>) iftable[i]; 642 Method result = ifc.getPublicMethodRecursive(name, parameterTypes); 643 if (result != null && Modifier.isPublic(result.getAccessFlags())) { 644 return result; 645 } 646 } 647 } 648 return null; 649 } 650 651 /** 652 * Returns the method if it is defined by this class; {@code null} otherwise. This may return a 653 * non-public member. 654 * 655 * @param name the method name 656 * @param args the method's parameter types 657 */ getDeclaredMethodInternal(String name, Class<?>[] args)658 private native Method getDeclaredMethodInternal(String name, Class<?>[] args); 659 660 /** 661 * Returns an array containing {@code Method} objects for all methods 662 * declared in the class represented by this {@code Class}. If there are no 663 * methods or if this {@code Class} represents an array class, a primitive 664 * type or void then an empty array is returned. 665 * 666 * @see #getMethods() 667 */ getDeclaredMethods()668 public Method[] getDeclaredMethods() { 669 Method[] result = getDeclaredMethodsUnchecked(false); 670 for (Method m : result) { 671 // Throw NoClassDefFoundError if types cannot be resolved. 672 m.getReturnType(); 673 m.getParameterTypes(); 674 } 675 return result; 676 677 } 678 679 /** 680 * Populates a list of methods without performing any security or type 681 * resolution checks first. If no methods exist, the list is not modified. 682 * 683 * @param publicOnly Whether to return only public methods. 684 * @param methods A list to populate with declared methods. 685 * @hide 686 */ getDeclaredMethodsUnchecked(boolean publicOnly)687 public native Method[] getDeclaredMethodsUnchecked(boolean publicOnly); 688 689 /** 690 * Returns an array containing {@code Method} objects for all public methods 691 * for the class C represented by this {@code Class}. Methods may be 692 * declared in C, the interfaces it implements or in the superclasses of C. 693 * The elements in the returned array are in no particular order. 694 * 695 * <p>If there are no public methods or if this {@code Class} represents a 696 * primitive type or {@code void} then an empty array is returned. 697 * 698 * @see #getDeclaredMethods() 699 */ getMethods()700 public Method[] getMethods() { 701 List<Method> methods = new ArrayList<Method>(); 702 getPublicMethodsInternal(methods); 703 /* 704 * Remove duplicate methods defined by superclasses and 705 * interfaces, preferring to keep methods declared by derived 706 * types. 707 */ 708 CollectionUtils.removeDuplicates(methods, Method.ORDER_BY_SIGNATURE); 709 return methods.toArray(new Method[methods.size()]); 710 } 711 712 /** 713 * Populates {@code result} with public methods defined by this class, its 714 * superclasses, and all implemented interfaces, including overridden methods. 715 */ getPublicMethodsInternal(List<Method> result)716 private void getPublicMethodsInternal(List<Method> result) { 717 Collections.addAll(result, getDeclaredMethodsUnchecked(true)); 718 if (!isInterface()) { 719 // Search superclasses, for interfaces don't search java.lang.Object. 720 for (Class<?> c = superClass; c != null; c = c.superClass) { 721 Collections.addAll(result, c.getDeclaredMethodsUnchecked(true)); 722 } 723 } 724 // Search iftable which has a flattened and uniqued list of interfaces. 725 Object[] iftable = ifTable; 726 if (iftable != null) { 727 for (int i = 0; i < iftable.length; i += 2) { 728 Class<?> ifc = (Class<?>) iftable[i]; 729 Collections.addAll(result, ifc.getDeclaredMethodsUnchecked(true)); 730 } 731 } 732 } 733 734 /** 735 * Returns the annotations that are directly defined on the class 736 * represented by this {@code Class}. Annotations that are inherited are not 737 * included in the result. If there are no annotations at all, an empty 738 * array is returned. 739 * 740 * @see #getAnnotations() 741 */ getDeclaredAnnotations()742 @Override public Annotation[] getDeclaredAnnotations() { 743 List<Annotation> result = AnnotationAccess.getDeclaredAnnotations(this); 744 return result.toArray(new Annotation[result.size()]); 745 } 746 747 /** 748 * Returns an array containing {@code Class} objects for all classes, 749 * interfaces, enums and annotations that are members of this class. 750 */ getDeclaredClasses()751 public Class<?>[] getDeclaredClasses() { 752 return AnnotationAccess.getMemberClasses(this); 753 } 754 755 /** 756 * Returns a {@code Field} object for the field with the given name 757 * which is declared in the class represented by this {@code Class}. 758 * 759 * @throws NoSuchFieldException if the requested field can not be found. 760 * @see #getField(String) 761 */ getDeclaredField(String name)762 public native Field getDeclaredField(String name) throws NoSuchFieldException; 763 764 /** 765 * Returns an array containing {@code Field} objects for all fields declared 766 * in the class represented by this {@code Class}. If there are no fields or 767 * if this {@code Class} represents an array class, a primitive type or void 768 * then an empty array is returned. 769 * 770 * @see #getFields() 771 */ getDeclaredFields()772 public native Field[] getDeclaredFields(); 773 774 /** 775 * Populates a list of fields without performing any security or type 776 * resolution checks first. If no fields exist, the list is not modified. 777 * 778 * @param publicOnly Whether to return only public fields. 779 * @param fields A list to populate with declared fields. 780 * @hide 781 */ getDeclaredFieldsUnchecked(boolean publicOnly)782 public native Field[] getDeclaredFieldsUnchecked(boolean publicOnly); 783 784 /** 785 * Returns the field if it is defined by this class; {@code null} otherwise. This 786 * may return a non-public member. 787 */ getDeclaredFieldInternal(String name)788 private native Field getDeclaredFieldInternal(String name); 789 790 /** 791 * Returns the subset of getDeclaredFields which are public. 792 */ getPublicDeclaredFields()793 private native Field[] getPublicDeclaredFields(); 794 795 /** 796 * Returns the class that this class is a member of, or {@code null} if this 797 * class is a top-level class, a primitive, an array, or defined within a 798 * method or constructor. 799 */ getDeclaringClass()800 public Class<?> getDeclaringClass() { 801 if (AnnotationAccess.isAnonymousClass(this)) { 802 return null; 803 } 804 return AnnotationAccess.getEnclosingClass(this); 805 } 806 807 /** 808 * Returns the class enclosing this class. For most classes this is the same 809 * as the {@link #getDeclaringClass() declaring class}. For classes defined 810 * within a method or constructor (typically anonymous inner classes), this 811 * is the declaring class of that member. 812 */ getEnclosingClass()813 public Class<?> getEnclosingClass() { 814 Class<?> declaringClass = getDeclaringClass(); 815 if (declaringClass != null) { 816 return declaringClass; 817 } 818 AccessibleObject member = AnnotationAccess.getEnclosingMethodOrConstructor(this); 819 if (member != null) { 820 return ((Member) member).getDeclaringClass(); 821 } 822 return AnnotationAccess.getEnclosingClass(this); 823 } 824 825 /** 826 * Returns the enclosing {@code Constructor} of this {@code Class}, if it is an 827 * anonymous or local/automatic class; otherwise {@code null}. 828 */ getEnclosingConstructor()829 public Constructor<?> getEnclosingConstructor() { 830 if (classNameImpliesTopLevel()) { 831 return null; 832 } 833 AccessibleObject result = AnnotationAccess.getEnclosingMethodOrConstructor(this); 834 return result instanceof Constructor ? (Constructor<?>) result : null; 835 } 836 837 /** 838 * Returns the enclosing {@code Method} of this {@code Class}, if it is an 839 * anonymous or local/automatic class; otherwise {@code null}. 840 */ getEnclosingMethod()841 public Method getEnclosingMethod() { 842 if (classNameImpliesTopLevel()) { 843 return null; 844 } 845 AccessibleObject result = AnnotationAccess.getEnclosingMethodOrConstructor(this); 846 return result instanceof Method ? (Method) result : null; 847 } 848 849 /** 850 * Returns true if this class is definitely a top level class, or false if 851 * a more expensive check like {@link #getEnclosingClass()} is necessary. 852 * 853 * <p>This is a hack that exploits an implementation detail of all Java 854 * language compilers: generated names always contain "$". As it is possible 855 * for a top level class to be named with a "$", a false result <strong>does 856 * not</strong> indicate that this isn't a top-level class. 857 */ classNameImpliesTopLevel()858 private boolean classNameImpliesTopLevel() { 859 return !getName().contains("$"); 860 } 861 862 /** 863 * Returns the {@code enum} constants associated with this {@code Class}. 864 * Returns {@code null} if this {@code Class} does not represent an {@code 865 * enum} type. 866 */ 867 @SuppressWarnings("unchecked") // we only cast after confirming that this class is an enum getEnumConstants()868 public T[] getEnumConstants() { 869 if (!isEnum()) { 870 return null; 871 } 872 return (T[]) Enum.getSharedConstants((Class) this).clone(); 873 } 874 875 /** 876 * Returns a {@code Field} object which represents the public field with the 877 * given name. This method first searches the class C represented by 878 * this {@code Class}, then the interfaces implemented by C and finally the 879 * superclasses of C. 880 * 881 * @throws NoSuchFieldException 882 * if the field cannot be found. 883 * @see #getDeclaredField(String) 884 */ getField(String name)885 public Field getField(String name) throws NoSuchFieldException { 886 if (name == null) { 887 throw new NullPointerException("name == null"); 888 } 889 Field result = getPublicFieldRecursive(name); 890 if (result == null) { 891 throw new NoSuchFieldException(name); 892 } 893 return result; 894 } 895 getPublicFieldRecursive(String name)896 private Field getPublicFieldRecursive(String name) { 897 // search superclasses 898 for (Class<?> c = this; c != null; c = c.superClass) { 899 Field result = c.getDeclaredFieldInternal(name); 900 if (result != null && (result.getModifiers() & Modifier.PUBLIC) != 0) { 901 return result; 902 } 903 } 904 905 // search iftable which has a flattened and uniqued list of interfaces 906 if (ifTable != null) { 907 for (int i = 0; i < ifTable.length; i += 2) { 908 Field result = ((Class<?>) ifTable[i]).getPublicFieldRecursive(name); 909 if (result != null && (result.getModifiers() & Modifier.PUBLIC) != 0) { 910 return result; 911 } 912 } 913 } 914 915 return null; 916 } 917 918 /** 919 * Returns an array containing {@code Field} objects for all public fields 920 * for the class C represented by this {@code Class}. Fields may be declared 921 * in C, the interfaces it implements or in the superclasses of C. The 922 * elements in the returned array are in no particular order. 923 * 924 * <p>If there are no public fields or if this class represents an array class, 925 * a primitive type or {@code void} then an empty array is returned. 926 * 927 * @see #getDeclaredFields() 928 */ getFields()929 public Field[] getFields() { 930 List<Field> fields = new ArrayList<Field>(); 931 getPublicFieldsRecursive(fields); 932 return fields.toArray(new Field[fields.size()]); 933 } 934 935 /** 936 * Populates {@code result} with public fields defined by this class, its 937 * superclasses, and all implemented interfaces. 938 */ getPublicFieldsRecursive(List<Field> result)939 private void getPublicFieldsRecursive(List<Field> result) { 940 // search superclasses 941 for (Class<?> c = this; c != null; c = c.superClass) { 942 Collections.addAll(result, c.getPublicDeclaredFields()); 943 } 944 945 // search iftable which has a flattened and uniqued list of interfaces 946 Object[] iftable = ifTable; 947 if (iftable != null) { 948 for (int i = 0; i < iftable.length; i += 2) { 949 Collections.addAll(result, ((Class<?>) iftable[i]).getPublicDeclaredFields()); 950 } 951 } 952 } 953 954 /** 955 * Returns the {@link Type}s of the interfaces that this {@code Class} directly 956 * implements. If the {@code Class} represents a primitive type or {@code 957 * void} then an empty array is returned. 958 */ getGenericInterfaces()959 public Type[] getGenericInterfaces() { 960 Type[] result; 961 synchronized (Caches.genericInterfaces) { 962 result = Caches.genericInterfaces.get(this); 963 if (result == null) { 964 String annotationSignature = AnnotationAccess.getSignature(this); 965 if (annotationSignature == null) { 966 result = getInterfaces(); 967 } else { 968 GenericSignatureParser parser = new GenericSignatureParser(getClassLoader()); 969 parser.parseForClass(this, annotationSignature); 970 result = Types.getTypeArray(parser.interfaceTypes, false); 971 } 972 Caches.genericInterfaces.put(this, result); 973 } 974 } 975 return (result.length == 0) ? result : result.clone(); 976 } 977 978 /** 979 * Returns the {@code Type} that represents the superclass of this {@code 980 * class}. 981 */ getGenericSuperclass()982 public Type getGenericSuperclass() { 983 Type genericSuperclass = getSuperclass(); 984 // This method is specified to return null for all cases where getSuperclass 985 // returns null, i.e, for primitives, interfaces, void and java.lang.Object. 986 if (genericSuperclass == null) { 987 return null; 988 } 989 990 String annotationSignature = AnnotationAccess.getSignature(this); 991 if (annotationSignature != null) { 992 GenericSignatureParser parser = new GenericSignatureParser(getClassLoader()); 993 parser.parseForClass(this, annotationSignature); 994 genericSuperclass = parser.superclassType; 995 } 996 return Types.getType(genericSuperclass); 997 } 998 999 /** 1000 * Returns an array of {@code Class} objects that match the interfaces 1001 * in the {@code implements} declaration of the class represented 1002 * by this {@code Class}. The order of the elements in the array is 1003 * identical to the order in the original class declaration. If the class 1004 * does not implement any interfaces, an empty array is returned. 1005 * 1006 * <p>This method only returns directly-implemented interfaces, and does not 1007 * include interfaces implemented by superclasses or superinterfaces of any 1008 * implemented interfaces. 1009 */ getInterfaces()1010 public Class<?>[] getInterfaces() { 1011 if (isArray()) { 1012 return new Class<?>[] { Cloneable.class, Serializable.class }; 1013 } else if (isProxy()) { 1014 return getProxyInterfaces(); 1015 } 1016 Dex dex = getDex(); 1017 if (dex == null) { 1018 return EmptyArray.CLASS; 1019 } 1020 short[] interfaces = dex.interfaceTypeIndicesFromClassDefIndex(dexClassDefIndex); 1021 Class<?>[] result = new Class<?>[interfaces.length]; 1022 for (int i = 0; i < interfaces.length; i++) { 1023 result[i] = getDexCacheType(dex, interfaces[i]); 1024 } 1025 return result; 1026 } 1027 1028 // Returns the interfaces that this proxy class directly implements. getProxyInterfaces()1029 private native Class<?>[] getProxyInterfaces(); 1030 1031 /** 1032 * Returns an integer that represents the modifiers of the class represented 1033 * by this {@code Class}. The returned value is a combination of bits 1034 * defined by constants in the {@link Modifier} class. 1035 */ getModifiers()1036 public int getModifiers() { 1037 // Array classes inherit modifiers from their component types, but in the case of arrays 1038 // of an inner class, the class file may contain "fake" access flags because it's not valid 1039 // for a top-level class to private, say. The real access flags are stored in the InnerClass 1040 // attribute, so we need to make sure we drill down to the inner class: the accessFlags 1041 // field is not the value we want to return, and the synthesized array class does not itself 1042 // have an InnerClass attribute. https://code.google.com/p/android/issues/detail?id=56267 1043 if (isArray()) { 1044 int componentModifiers = getComponentType().getModifiers(); 1045 if ((componentModifiers & Modifier.INTERFACE) != 0) { 1046 componentModifiers &= ~(Modifier.INTERFACE | Modifier.STATIC); 1047 } 1048 return Modifier.ABSTRACT | Modifier.FINAL | componentModifiers; 1049 } 1050 int JAVA_FLAGS_MASK = 0xffff; 1051 int modifiers = AnnotationAccess.getInnerClassFlags(this, accessFlags & JAVA_FLAGS_MASK); 1052 return modifiers & JAVA_FLAGS_MASK; 1053 } 1054 1055 /** 1056 * Returns the name of the class represented by this {@code Class}. For a 1057 * description of the format which is used, see the class definition of 1058 * {@link Class}. 1059 */ getName()1060 public String getName() { 1061 String result = name; 1062 return (result == null) ? (name = getNameNative()) : result; 1063 } 1064 getNameNative()1065 private native String getNameNative(); 1066 1067 /** 1068 * Returns the simple name of the class represented by this {@code Class} as 1069 * defined in the source code. If there is no name (that is, the class is 1070 * anonymous) then an empty string is returned. If the receiver is an array 1071 * then the name of the underlying type with square braces appended (for 1072 * example {@code "Integer[]"}) is returned. 1073 * 1074 * @return the simple name of the class represented by this {@code Class}. 1075 */ getSimpleName()1076 public String getSimpleName() { 1077 if (isArray()) { 1078 return getComponentType().getSimpleName() + "[]"; 1079 } 1080 1081 if (isAnonymousClass()) { 1082 return ""; 1083 } 1084 1085 if (isMemberClass() || isLocalClass()) { 1086 return getInnerClassName(); 1087 } 1088 1089 String name = getName(); 1090 int dot = name.lastIndexOf('.'); 1091 if (dot != -1) { 1092 return name.substring(dot + 1); 1093 } 1094 1095 return name; 1096 } 1097 1098 /** 1099 * Returns the simple name of a member or local class, or {@code null} otherwise. 1100 */ getInnerClassName()1101 private String getInnerClassName() { 1102 return AnnotationAccess.getInnerClassName(this); 1103 } 1104 1105 /** 1106 * Returns {@code null}. 1107 */ getProtectionDomain()1108 public ProtectionDomain getProtectionDomain() { 1109 return null; 1110 } 1111 1112 /** 1113 * Returns the URL of the given resource, or {@code null} if the resource is not found. 1114 * The mapping between the resource name and the URL is managed by the class' class loader. 1115 * 1116 * @see ClassLoader 1117 */ getResource(String resourceName)1118 public URL getResource(String resourceName) { 1119 // Get absolute resource name, but without the leading slash 1120 if (resourceName.startsWith("/")) { 1121 resourceName = resourceName.substring(1); 1122 } else { 1123 String pkg = getName(); 1124 int dot = pkg.lastIndexOf('.'); 1125 if (dot != -1) { 1126 pkg = pkg.substring(0, dot).replace('.', '/'); 1127 } else { 1128 pkg = ""; 1129 } 1130 1131 resourceName = pkg + "/" + resourceName; 1132 } 1133 1134 // Delegate to proper class loader 1135 ClassLoader loader = getClassLoader(); 1136 if (loader != null) { 1137 return loader.getResource(resourceName); 1138 } else { 1139 return ClassLoader.getSystemResource(resourceName); 1140 } 1141 } 1142 1143 /** 1144 * Returns a read-only stream for the contents of the given resource, or {@code null} if the 1145 * resource is not found. 1146 * The mapping between the resource name and the stream is managed by the class' class loader. 1147 * 1148 * @see ClassLoader 1149 */ getResourceAsStream(String resourceName)1150 public InputStream getResourceAsStream(String resourceName) { 1151 // Get absolute resource name, but without the leading slash 1152 if (resourceName.startsWith("/")) { 1153 resourceName = resourceName.substring(1); 1154 } else { 1155 String pkg = getName(); 1156 int dot = pkg.lastIndexOf('.'); 1157 if (dot != -1) { 1158 pkg = pkg.substring(0, dot).replace('.', '/'); 1159 } else { 1160 pkg = ""; 1161 } 1162 1163 resourceName = pkg + "/" + resourceName; 1164 } 1165 1166 // Delegate to proper class loader 1167 ClassLoader loader = getClassLoader(); 1168 if (loader != null) { 1169 return loader.getResourceAsStream(resourceName); 1170 } else { 1171 return ClassLoader.getSystemResourceAsStream(resourceName); 1172 } 1173 } 1174 1175 /** 1176 * Returns {@code null}. (On Android, a {@code ClassLoader} can load classes from multiple dex 1177 * files. All classes from any given dex file will have the same signers, but different dex 1178 * files may have different signers. This does not fit well with the original 1179 * {@code ClassLoader}-based model of {@code getSigners}.) 1180 */ getSigners()1181 public Object[] getSigners() { 1182 // See http://code.google.com/p/android/issues/detail?id=1766. 1183 return null; 1184 } 1185 1186 /** 1187 * Returns the {@code Class} object which represents the superclass of the 1188 * class represented by this {@code Class}. If this {@code Class} represents 1189 * the {@code Object} class, a primitive type, an interface or void then the 1190 * method returns {@code null}. If this {@code Class} represents an array 1191 * class then the {@code Object} class is returned. 1192 */ getSuperclass()1193 public Class<? super T> getSuperclass() { 1194 // For interfaces superClass is Object (which agrees with the JNI spec) 1195 // but not with the expected behavior here. 1196 if (isInterface()) { 1197 return null; 1198 } else { 1199 return superClass; 1200 } 1201 } 1202 1203 /** 1204 * Returns an array containing {@code TypeVariable} objects for type 1205 * variables declared by the generic class represented by this {@code 1206 * Class}. Returns an empty array if the class is not generic. 1207 */ 1208 @SuppressWarnings("unchecked") getTypeParameters()1209 @Override public synchronized TypeVariable<Class<T>>[] getTypeParameters() { 1210 String annotationSignature = AnnotationAccess.getSignature(this); 1211 if (annotationSignature == null) { 1212 return EmptyArray.TYPE_VARIABLE; 1213 } 1214 GenericSignatureParser parser = new GenericSignatureParser(getClassLoader()); 1215 parser.parseForClass(this, annotationSignature); 1216 return parser.formalTypeParameters; 1217 } 1218 1219 /** 1220 * Tests whether this {@code Class} represents an annotation class. 1221 */ isAnnotation()1222 public boolean isAnnotation() { 1223 final int ACC_ANNOTATION = 0x2000; // not public in reflect.Modifier 1224 return (accessFlags & ACC_ANNOTATION) != 0; 1225 } 1226 isAnnotationPresent(Class<? extends Annotation> annotationType)1227 @Override public boolean isAnnotationPresent(Class<? extends Annotation> annotationType) { 1228 return AnnotationAccess.isAnnotationPresent(this, annotationType); 1229 } 1230 1231 /** 1232 * Tests whether the class represented by this {@code Class} is 1233 * anonymous. 1234 */ isAnonymousClass()1235 public boolean isAnonymousClass() { 1236 return AnnotationAccess.isAnonymousClass(this); 1237 } 1238 1239 /** 1240 * Tests whether the class represented by this {@code Class} is an array class. 1241 */ isArray()1242 public boolean isArray() { 1243 return getComponentType() != null; 1244 } 1245 1246 /** 1247 * Is this a runtime created proxy class? 1248 * 1249 * @hide 1250 */ isProxy()1251 public boolean isProxy() { 1252 return (accessFlags & 0x00040000) != 0; 1253 } 1254 1255 /** 1256 * Can {@code c} be assigned to this class? For example, String can be assigned to Object 1257 * (by an upcast), however, an Object cannot be assigned to a String as a potentially exception 1258 * throwing downcast would be necessary. Similarly for interfaces, a class that implements (or 1259 * an interface that extends) another can be assigned to its parent, but not vice-versa. All 1260 * Classes may assign to themselves. Classes for primitive types may not assign to each other. 1261 * 1262 * @param c the class to check. 1263 * @return {@code true} if {@code c} can be assigned to the class 1264 * represented by this {@code Class}; {@code false} otherwise. 1265 * @throws NullPointerException if {@code c} is {@code null}. 1266 */ isAssignableFrom(Class<?> c)1267 public boolean isAssignableFrom(Class<?> c) { 1268 if (this == c) { 1269 return true; // Can always assign to things of the same type. 1270 } else if (this == Object.class) { 1271 return !c.isPrimitive(); // Can assign any reference to java.lang.Object. 1272 } else if (isArray()) { 1273 return c.isArray() && componentType.isAssignableFrom(c.componentType); 1274 } else if (isInterface()) { 1275 // Search iftable which has a flattened and uniqued list of interfaces. 1276 Object[] iftable = c.ifTable; 1277 if (iftable != null) { 1278 for (int i = 0; i < iftable.length; i += 2) { 1279 if (iftable[i] == this) { 1280 return true; 1281 } 1282 } 1283 } 1284 return false; 1285 } else { 1286 if (!c.isInterface()) { 1287 for (c = c.superClass; c != null; c = c.superClass) { 1288 if (c == this) { 1289 return true; 1290 } 1291 } 1292 } 1293 return false; 1294 } 1295 } 1296 1297 /** 1298 * Tests whether the class represented by this {@code Class} is an 1299 * {@code enum}. 1300 */ isEnum()1301 public boolean isEnum() { 1302 return (getSuperclass() == Enum.class) && ((accessFlags & 0x4000) != 0); 1303 } 1304 1305 /** 1306 * Tests whether the given object can be cast to the class 1307 * represented by this {@code Class}. This is the runtime version of the 1308 * {@code instanceof} operator. 1309 * 1310 * @return {@code true} if {@code object} can be cast to the type 1311 * represented by this {@code Class}; {@code false} if {@code 1312 * object} is {@code null} or cannot be cast. 1313 */ isInstance(Object object)1314 public boolean isInstance(Object object) { 1315 if (object == null) { 1316 return false; 1317 } 1318 return isAssignableFrom(object.getClass()); 1319 } 1320 1321 /** 1322 * Tests whether this {@code Class} represents an interface. 1323 */ isInterface()1324 public boolean isInterface() { 1325 return (accessFlags & Modifier.INTERFACE) != 0; 1326 } 1327 1328 /** 1329 * Tests whether the class represented by this {@code Class} is defined 1330 * locally. 1331 */ isLocalClass()1332 public boolean isLocalClass() { 1333 return !classNameImpliesTopLevel() 1334 && AnnotationAccess.getEnclosingMethodOrConstructor(this) != null 1335 && !isAnonymousClass(); 1336 } 1337 1338 /** 1339 * Tests whether the class represented by this {@code Class} is a member 1340 * class. 1341 */ isMemberClass()1342 public boolean isMemberClass() { 1343 return getDeclaringClass() != null; 1344 } 1345 1346 /** 1347 * Tests whether this {@code Class} represents a primitive type. 1348 */ isPrimitive()1349 public boolean isPrimitive() { 1350 return (primitiveType & 0xFFFF) != 0; 1351 } 1352 1353 /** 1354 * Tests whether this {@code Class} represents a synthetic type. 1355 */ isSynthetic()1356 public boolean isSynthetic() { 1357 final int ACC_SYNTHETIC = 0x1000; // not public in reflect.Modifier 1358 return (accessFlags & ACC_SYNTHETIC) != 0; 1359 } 1360 1361 /** 1362 * Indicates whether this {@code Class} or its parents override finalize. 1363 * 1364 * @hide 1365 */ isFinalizable()1366 public boolean isFinalizable() { 1367 final int ACC_CLASS_IS_FINALIZABLE = 0x80000000; // not public in reflect.Modifier 1368 return (accessFlags & ACC_CLASS_IS_FINALIZABLE) != 0; 1369 } 1370 1371 /** 1372 * Returns a new instance of the class represented by this {@code Class}, 1373 * created by invoking the default (that is, zero-argument) constructor. If 1374 * there is no such constructor, or if the creation fails (either because of 1375 * a lack of available memory or because an exception is thrown by the 1376 * constructor), an {@code InstantiationException} is thrown. If the default 1377 * constructor exists but is not accessible from the context where this 1378 * method is invoked, an {@code IllegalAccessException} is thrown. 1379 * 1380 * @throws IllegalAccessException 1381 * if the default constructor is not visible. 1382 * @throws InstantiationException 1383 * if the instance cannot be created. 1384 */ newInstance()1385 public native T newInstance() throws InstantiationException, IllegalAccessException; 1386 canAccess(Class<?> c)1387 private boolean canAccess(Class<?> c) { 1388 if(Modifier.isPublic(c.accessFlags)) { 1389 return true; 1390 } 1391 return inSamePackage(c); 1392 } 1393 canAccessMember(Class<?> memberClass, int memberModifiers)1394 private boolean canAccessMember(Class<?> memberClass, int memberModifiers) { 1395 if (memberClass == this || Modifier.isPublic(memberModifiers)) { 1396 return true; 1397 } 1398 if (Modifier.isPrivate(memberModifiers)) { 1399 return false; 1400 } 1401 if (Modifier.isProtected(memberModifiers)) { 1402 for (Class<?> parent = this.superClass; parent != null; parent = parent.superClass) { 1403 if (parent == memberClass) { 1404 return true; 1405 } 1406 } 1407 } 1408 return inSamePackage(memberClass); 1409 } 1410 inSamePackage(Class<?> c)1411 private boolean inSamePackage(Class<?> c) { 1412 if (classLoader != c.classLoader) { 1413 return false; 1414 } 1415 String packageName1 = getPackageName$(); 1416 String packageName2 = c.getPackageName$(); 1417 if (packageName1 == null) { 1418 return packageName2 == null; 1419 } else if (packageName2 == null) { 1420 return false; 1421 } else { 1422 return packageName1.equals(packageName2); 1423 } 1424 } 1425 1426 @Override toString()1427 public String toString() { 1428 if (isPrimitive()) { 1429 return getSimpleName(); 1430 } else { 1431 return (isInterface() ? "interface " : "class ") + getName(); 1432 } 1433 } 1434 1435 /** 1436 * Returns the {@code Package} of which the class represented by this 1437 * {@code Class} is a member. Returns {@code null} if no {@code Package} 1438 * object was created by the class loader of the class. 1439 */ getPackage()1440 public Package getPackage() { 1441 // TODO This might be a hack, but the runtime doesn't have the necessary info. 1442 ClassLoader loader = getClassLoader(); 1443 if (loader != null) { 1444 String packageName = getPackageName$(); 1445 return packageName != null ? loader.getPackage(packageName) : null; 1446 } 1447 return null; 1448 } 1449 1450 /** 1451 * Returns the package name of this class. This returns {@code null} for classes in 1452 * the default package. 1453 * 1454 * @hide 1455 */ getPackageName$()1456 public String getPackageName$() { 1457 String name = getName(); 1458 int last = name.lastIndexOf('.'); 1459 return last == -1 ? null : name.substring(0, last); 1460 } 1461 1462 /** 1463 * Returns the assertion status for the class represented by this {@code 1464 * Class}. Assertion is enabled / disabled based on the class loader, 1465 * package or class default at runtime. 1466 */ desiredAssertionStatus()1467 public boolean desiredAssertionStatus() { 1468 return false; 1469 } 1470 1471 /** 1472 * Casts this {@code Class} to represent a subclass of the given class. 1473 * If successful, this {@code Class} is returned; otherwise a {@code 1474 * ClassCastException} is thrown. 1475 * 1476 * @throws ClassCastException 1477 * if this {@code Class} cannot be cast to the given type. 1478 */ 1479 @SuppressWarnings("unchecked") asSubclass(Class<U> c)1480 public <U> Class<? extends U> asSubclass(Class<U> c) { 1481 if (c.isAssignableFrom(this)) { 1482 return (Class<? extends U>)this; 1483 } 1484 String actualClassName = this.getName(); 1485 String desiredClassName = c.getName(); 1486 throw new ClassCastException(actualClassName + " cannot be cast to " + desiredClassName); 1487 } 1488 1489 /** 1490 * Casts the given object to the type represented by this {@code Class}. 1491 * If the object is {@code null} then the result is also {@code null}. 1492 * 1493 * @throws ClassCastException 1494 * if the object cannot be cast to the given type. 1495 */ 1496 @SuppressWarnings("unchecked") cast(Object obj)1497 public T cast(Object obj) { 1498 if (obj == null) { 1499 return null; 1500 } else if (this.isInstance(obj)) { 1501 return (T)obj; 1502 } 1503 String actualClassName = obj.getClass().getName(); 1504 String desiredClassName = this.getName(); 1505 throw new ClassCastException(actualClassName + " cannot be cast to " + desiredClassName); 1506 } 1507 1508 /** 1509 * The class def of this class in its own Dex, or -1 if there is no class def. 1510 * 1511 * @hide 1512 */ getDexClassDefIndex()1513 public int getDexClassDefIndex() { 1514 return (dexClassDefIndex == 65535) ? -1 : dexClassDefIndex; 1515 } 1516 1517 /** 1518 * The type index of this class in its own Dex, or -1 if it is unknown. If a class is referenced 1519 * by multiple Dex files, it will have a different type index in each. Dex files support 65534 1520 * type indices, with 65535 representing no index. 1521 * 1522 * @hide 1523 */ getDexTypeIndex()1524 public int getDexTypeIndex() { 1525 int typeIndex = dexTypeIndex; 1526 if (typeIndex != 65535) { 1527 return typeIndex; 1528 } 1529 synchronized (this) { 1530 typeIndex = dexTypeIndex; 1531 if (typeIndex == 65535) { 1532 if (dexClassDefIndex >= 0) { 1533 typeIndex = getDex().typeIndexFromClassDefIndex(dexClassDefIndex); 1534 } else { 1535 typeIndex = getDex().findTypeIndex(InternalNames.getInternalName(this)); 1536 if (typeIndex < 0) { 1537 typeIndex = -1; 1538 } 1539 } 1540 dexTypeIndex = typeIndex; 1541 } 1542 } 1543 return typeIndex; 1544 } 1545 1546 /** 1547 * The annotation directory offset of this class in its own Dex, or 0 if it 1548 * is unknown. 1549 * 1550 * TODO: 0 is a sentinel that means 'no annotations directory'; this should be -1 if unknown 1551 * 1552 * @hide 1553 */ getDexAnnotationDirectoryOffset()1554 public int getDexAnnotationDirectoryOffset() { 1555 Dex dex = getDex(); 1556 if (dex == null) { 1557 return 0; 1558 } 1559 int classDefIndex = getDexClassDefIndex(); 1560 if (classDefIndex < 0) { 1561 return 0; 1562 } 1563 return dex.annotationDirectoryOffsetFromClassDefIndex(classDefIndex); 1564 } 1565 1566 private static class Caches { 1567 /** 1568 * Cache to avoid frequent recalculation of generic interfaces, which is generally uncommon. 1569 * Sized sufficient to allow ConcurrentHashMapTest to run without recalculating its generic 1570 * interfaces (required to avoid time outs). Validated by running reflection heavy code 1571 * such as applications using Guice-like frameworks. 1572 */ 1573 private static final BasicLruCache<Class, Type[]> genericInterfaces 1574 = new BasicLruCache<Class, Type[]>(8); 1575 } 1576 } 1577