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.ArtField; 43 import java.lang.reflect.ArtMethod; 44 import java.lang.reflect.Constructor; 45 import java.lang.reflect.Field; 46 import java.lang.reflect.GenericDeclaration; 47 import java.lang.reflect.InvocationTargetException; 48 import java.lang.reflect.Member; 49 import java.lang.reflect.Method; 50 import java.lang.reflect.Modifier; 51 import java.lang.reflect.Type; 52 import java.lang.reflect.TypeVariable; 53 import java.net.URL; 54 import java.security.ProtectionDomain; 55 import java.util.ArrayList; 56 import java.util.Arrays; 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 VM-generated classes 136 * e.g. arrays and primitive classes. 137 */ 138 private transient DexCache dexCache; 139 140 /** static, private, and <init> methods. */ 141 private transient ArtMethod[] directMethods; 142 143 /** 144 * Instance fields. These describe the layout of the contents of an Object. Note that only the 145 * fields directly declared by this class are listed in iFields; fields declared by a 146 * superclass are listed in the superclass's Class.iFields. 147 * 148 * All instance fields that refer to objects are guaranteed to be at the beginning of the field 149 * list. {@link Class#numReferenceInstanceFields} specifies the number of reference fields. 150 */ 151 private transient ArtField[] iFields; 152 153 /** 154 * The interface table (iftable_) contains pairs of a interface class and an array of the 155 * interface methods. There is one pair per interface supported by this class. That 156 * means one pair for each interface we support directly, indirectly via superclass, or 157 * indirectly via a superinterface. This will be null if neither we nor our superclass 158 * implement any interfaces. 159 * 160 * Why we need this: given "class Foo implements Face", declare "Face faceObj = new Foo()". 161 * Invoke faceObj.blah(), where "blah" is part of the Face interface. We can't easily use a 162 * single vtable. 163 * 164 * For every interface a concrete class implements, we create an array of the concrete vtable_ 165 * methods for the methods in the interface. 166 */ 167 private transient Object[] ifTable; 168 169 /** Interface method table (imt), for quick "invoke-interface". */ 170 private transient ArtMethod[] imTable; 171 172 /** Lazily computed name of this class; always prefer calling getName(). */ 173 private transient String name; 174 175 /** Static fields */ 176 private transient ArtField[] sFields; 177 178 /** The superclass, or NULL if this is java.lang.Object, an interface or primitive type. */ 179 private transient Class<? super T> superClass; 180 181 /** If class verify fails, we must return same error on subsequent tries. */ 182 private transient Class<?> verifyErrorClass; 183 184 /** Virtual methods defined in this class; invoked through vtable. */ 185 private transient ArtMethod[] virtualMethods; 186 187 /** 188 * Virtual method table (vtable), for use by "invoke-virtual". The vtable from the superclass 189 * is copied in, and virtual methods from our class either replace those from the super or are 190 * appended. For abstract classes, methods may be created in the vtable that aren't in 191 * virtual_ methods_ for miranda methods. 192 */ 193 private transient ArtMethod[] vtable; 194 195 /** access flags; low 16 bits are defined by VM spec */ 196 private transient int accessFlags; 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 instance fields that are object references. */ 224 private transient int numReferenceInstanceFields; 225 226 /** Number of static fields that are object references. */ 227 private transient int numReferenceStaticFields; 228 229 /** 230 * Total object size; used when allocating storage on GC heap. For interfaces and abstract 231 * classes this will be zero. See also {@link Class#classSize}. 232 */ 233 private transient int objectSize; 234 235 /** Primitive type value, or 0 if not a primitive type; set for generated primitive classes. */ 236 private transient int primitiveType; 237 238 /** Bitmap of offsets of iFields. */ 239 private transient int referenceInstanceOffsets; 240 241 /** Bitmap of offsets of sFields. */ 242 private transient int referenceStaticOffsets; 243 244 /** State of class initialization */ 245 private transient int status; 246 Class()247 private Class() { 248 // Prevent this class to be instantiated, instance should be created by JVM only 249 } 250 251 /** 252 * Returns a {@code Class} object which represents the class with 253 * the given name. The name should be the name of a non-primitive 254 * class, as described in the {@link Class class definition}. 255 * Primitive types can not be found using this method; use {@code 256 * int.class} or {@code Integer.TYPE} instead. 257 * 258 * <p>If the class has not yet been loaded, it is loaded and initialized 259 * first. This is done through either the class loader of the calling class 260 * or one of its parent class loaders. It is possible that a static initializer is run as 261 * a result of this call. 262 * 263 * @throws ClassNotFoundException 264 * if the requested class cannot be found. 265 * @throws LinkageError 266 * if an error occurs during linkage 267 * @throws ExceptionInInitializerError 268 * if an exception occurs during static initialization of a 269 * class. 270 */ forName(String className)271 public static Class<?> forName(String className) throws ClassNotFoundException { 272 return forName(className, true, VMStack.getCallingClassLoader()); 273 } 274 275 /** 276 * Returns a {@code Class} object which represents the class with 277 * the given name. The name should be the name of a non-primitive 278 * class, as described in the {@link Class class definition}. 279 * Primitive types can not be found using this method; use {@code 280 * int.class} or {@code Integer.TYPE} instead. 281 * 282 * <p>If the class has not yet been loaded, it is loaded first, using the given class loader. 283 * If the class has not yet been initialized and {@code shouldInitialize} is true, 284 * the class will be initialized. 285 * 286 * @throws ClassNotFoundException 287 * if the requested class cannot be found. 288 * @throws LinkageError 289 * if an error occurs during linkage 290 * @throws ExceptionInInitializerError 291 * if an exception occurs during static initialization of a 292 * class. 293 */ forName(String className, boolean shouldInitialize, ClassLoader classLoader)294 public static Class<?> forName(String className, boolean shouldInitialize, 295 ClassLoader classLoader) throws ClassNotFoundException { 296 297 if (classLoader == null) { 298 classLoader = ClassLoader.getSystemClassLoader(); 299 } 300 // Catch an Exception thrown by the underlying native code. It wraps 301 // up everything inside a ClassNotFoundException, even if e.g. an 302 // Error occurred during initialization. This as a workaround for 303 // an ExceptionInInitializerError that's also wrapped. It is actually 304 // expected to be thrown. Maybe the same goes for other errors. 305 // Not wrapping up all the errors will break android though. 306 Class<?> result; 307 try { 308 result = classForName(className, shouldInitialize, classLoader); 309 } catch (ClassNotFoundException e) { 310 Throwable cause = e.getCause(); 311 if (cause instanceof LinkageError) { 312 throw (LinkageError) cause; 313 } 314 throw e; 315 } 316 return result; 317 } 318 classForName(String className, boolean shouldInitialize, ClassLoader classLoader)319 static native Class<?> classForName(String className, boolean shouldInitialize, 320 ClassLoader classLoader) throws ClassNotFoundException; 321 322 /** 323 * Returns an array containing {@code Class} objects for all 324 * public classes, interfaces, enums and annotations that are 325 * members of this class and its superclasses. This does not 326 * include classes of implemented interfaces. If there are no 327 * such class members or if this object represents a primitive 328 * type then an array of length 0 is returned. 329 */ getClasses()330 public Class<?>[] getClasses() { 331 List<Class<?>> result = new ArrayList<Class<?>>(); 332 for (Class<?> c = this; c != null; c = c.superClass) { 333 for (Class<?> member : c.getDeclaredClasses()) { 334 if (Modifier.isPublic(member.getModifiers())) { 335 result.add(member); 336 } 337 } 338 } 339 return result.toArray(new Class[result.size()]); 340 } 341 getAnnotation(Class<A> annotationType)342 @Override public <A extends Annotation> A getAnnotation(Class<A> annotationType) { 343 return AnnotationAccess.getAnnotation(this, annotationType); 344 } 345 346 /** 347 * Returns an array containing all the annotations of this class. If there are no annotations 348 * then an empty array is returned. 349 * 350 * @see #getDeclaredAnnotations() 351 */ getAnnotations()352 @Override public Annotation[] getAnnotations() { 353 return AnnotationAccess.getAnnotations(this); 354 } 355 356 /** 357 * Returns the canonical name of this class. If this class does not have a 358 * canonical name as defined in the Java Language Specification, then the 359 * method returns {@code null}. 360 */ getCanonicalName()361 public String getCanonicalName() { 362 if (isLocalClass() || isAnonymousClass()) 363 return null; 364 365 if (isArray()) { 366 /* 367 * The canonical name of an array type depends on the (existence of) 368 * the component type's canonical name. 369 */ 370 String name = getComponentType().getCanonicalName(); 371 if (name != null) { 372 return name + "[]"; 373 } 374 } else if (isMemberClass()) { 375 /* 376 * The canonical name of an inner class depends on the (existence 377 * of) the declaring class' canonical name. 378 */ 379 String name = getDeclaringClass().getCanonicalName(); 380 if (name != null) { 381 return name + "." + getSimpleName(); 382 } 383 } else { 384 /* 385 * The canonical name of a top-level class or primitive type is 386 * equal to the fully qualified name. 387 */ 388 return getName(); 389 } 390 391 /* 392 * Other classes don't have a canonical name. 393 */ 394 return null; 395 } 396 397 /** 398 * Returns the class loader which was used to load the class represented by 399 * this {@code Class}. Implementations are free to return {@code null} for 400 * classes that were loaded by the bootstrap class loader. The Android 401 * reference implementation, though, always returns a reference to an actual 402 * class loader. 403 */ getClassLoader()404 public ClassLoader getClassLoader() { 405 if (this.isPrimitive()) { 406 return null; 407 } 408 409 ClassLoader loader = getClassLoaderImpl(); 410 if (loader == null) { 411 loader = BootClassLoader.getInstance(); 412 } 413 return loader; 414 } 415 416 /** 417 * This must be provided by the VM vendor, as it is used by other provided 418 * class implementations in this package. Outside of this class, it is used 419 * by SecurityManager.classLoaderDepth(), 420 * currentClassLoader() and currentLoadedClass(). Return the ClassLoader for 421 * this Class without doing any security checks. The bootstrap ClassLoader 422 * is returned, unlike getClassLoader() which returns null in place of the 423 * bootstrap ClassLoader. 424 */ getClassLoaderImpl()425 ClassLoader getClassLoaderImpl() { 426 ClassLoader loader = classLoader; 427 return loader == null ? BootClassLoader.getInstance() : loader; 428 } 429 430 /** 431 * Returns a {@code Class} object which represents the component type if 432 * this class represents an array type. Returns {@code null} if this class 433 * does not represent an array type. The component type of an array type is 434 * the type of the elements of the array. 435 */ getComponentType()436 public Class<?> getComponentType() { 437 return componentType; 438 } 439 440 /** 441 * Returns the dex file from which this class was loaded. 442 * 443 * @hide 444 */ getDex()445 public Dex getDex() { 446 if (dexCache == null) { 447 return null; 448 } 449 return dexCache.getDex(); 450 } 451 452 /** 453 * Returns a string from the dex cache, computing the string from the dex file if necessary. 454 * 455 * @hide 456 */ getDexCacheString(Dex dex, int dexStringIndex)457 public String getDexCacheString(Dex dex, int dexStringIndex) { 458 String[] dexCacheStrings = dexCache.strings; 459 String s = dexCacheStrings[dexStringIndex]; 460 if (s == null) { 461 s = dex.strings().get(dexStringIndex).intern(); 462 dexCacheStrings[dexStringIndex] = s; 463 } 464 return s; 465 } 466 467 /** 468 * Returns a resolved type from the dex cache, computing the type from the dex file if 469 * necessary. 470 * 471 * @hide 472 */ getDexCacheType(Dex dex, int dexTypeIndex)473 public Class<?> getDexCacheType(Dex dex, int dexTypeIndex) { 474 Class<?>[] dexCacheResolvedTypes = dexCache.resolvedTypes; 475 Class<?> resolvedType = dexCacheResolvedTypes[dexTypeIndex]; 476 if (resolvedType == null) { 477 int descriptorIndex = dex.typeIds().get(dexTypeIndex); 478 String descriptor = getDexCacheString(dex, descriptorIndex); 479 resolvedType = InternalNames.getClass(getClassLoader(), descriptor); 480 dexCacheResolvedTypes[dexTypeIndex] = resolvedType; 481 } 482 return resolvedType; 483 } 484 485 /** 486 * Returns a {@code Constructor} object which represents the public 487 * constructor matching the given parameter types. 488 * {@code (Class[]) null} is equivalent to the empty array. 489 * 490 * @throws NoSuchMethodException 491 * if the constructor cannot be found. 492 * @see #getDeclaredConstructor(Class[]) 493 */ getConstructor(Class<?>.... parameterTypes)494 public Constructor<T> getConstructor(Class<?>... parameterTypes) throws NoSuchMethodException { 495 return getConstructor(parameterTypes, true); 496 } 497 498 /** 499 * Returns a {@code Constructor} object which represents the constructor 500 * matching the specified parameter types that is declared by the class 501 * represented by this {@code Class}. 502 * {@code (Class[]) null} is equivalent to the empty array. 503 * 504 * @throws NoSuchMethodException 505 * if the requested constructor cannot be found. 506 * @see #getConstructor(Class[]) 507 */ getDeclaredConstructor(Class<?>.... parameterTypes)508 public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes) 509 throws NoSuchMethodException { 510 return getConstructor(parameterTypes, false); 511 } 512 513 /** 514 * Returns a constructor with the given parameters. 515 * 516 * @param publicOnly true to only return public constructores. 517 * @param parameterTypes argument types to match the constructor's. 518 */ getConstructor(Class<?>[] parameterTypes, boolean publicOnly)519 private Constructor<T> getConstructor(Class<?>[] parameterTypes, boolean publicOnly) 520 throws NoSuchMethodException { 521 if (parameterTypes == null) { 522 parameterTypes = EmptyArray.CLASS; 523 } 524 for (Class<?> c : parameterTypes) { 525 if (c == null) { 526 throw new NoSuchMethodException("parameter type is null"); 527 } 528 } 529 Constructor<T> result = getDeclaredConstructorInternal(parameterTypes); 530 if (result == null || publicOnly && !Modifier.isPublic(result.getAccessFlags())) { 531 throw new NoSuchMethodException("<init> " + Arrays.toString(parameterTypes)); 532 } 533 return result; 534 } 535 536 /** 537 * Returns the constructor with the given parameters if it is defined by this class; null 538 * otherwise. This may return a non-public member. 539 * 540 * @param args the types of the parameters to the constructor. 541 */ getDeclaredConstructorInternal(Class<?>[] args)542 private Constructor<T> getDeclaredConstructorInternal(Class<?>[] args) { 543 if (directMethods != null) { 544 for (ArtMethod m : directMethods) { 545 int modifiers = m.getAccessFlags(); 546 if (Modifier.isStatic(modifiers)) { 547 // skip <clinit> which is a static constructor 548 continue; 549 } 550 if (!Modifier.isConstructor(modifiers)) { 551 continue; 552 } 553 if (!ArtMethod.equalConstructorParameters(m, args)) { 554 continue; 555 } 556 return new Constructor<T>(m); 557 } 558 } 559 return null; 560 } 561 562 /** 563 * Returns an array containing {@code Constructor} objects for all public 564 * constructors for this {@code Class}. If there 565 * are no public constructors or if this {@code Class} represents an array 566 * class, a primitive type or void then an empty array is returned. 567 * 568 * @see #getDeclaredConstructors() 569 */ getConstructors()570 public Constructor<?>[] getConstructors() { 571 ArrayList<Constructor<T>> constructors = new ArrayList(); 572 getDeclaredConstructors(true, constructors); 573 return constructors.toArray(new Constructor[constructors.size()]); 574 } 575 576 /** 577 * Returns an array containing {@code Constructor} objects for all 578 * constructors declared in the class represented by this {@code Class}. If 579 * there are no constructors or if this {@code Class} represents an array 580 * class, a primitive type or void then an empty array is returned. 581 * 582 * @see #getConstructors() 583 */ getDeclaredConstructors()584 public Constructor<?>[] getDeclaredConstructors() { 585 ArrayList<Constructor<T>> constructors = new ArrayList(); 586 getDeclaredConstructors(false, constructors); 587 return constructors.toArray(new Constructor[constructors.size()]); 588 } 589 getDeclaredConstructors(boolean publicOnly, List<Constructor<T>> constructors)590 private void getDeclaredConstructors(boolean publicOnly, List<Constructor<T>> constructors) { 591 if (directMethods != null) { 592 for (ArtMethod m : directMethods) { 593 int modifiers = m.getAccessFlags(); 594 if (!publicOnly || Modifier.isPublic(modifiers)) { 595 if (Modifier.isStatic(modifiers)) { 596 // skip <clinit> which is a static constructor 597 continue; 598 } 599 if (Modifier.isConstructor(modifiers)) { 600 constructors.add(new Constructor<T>(m)); 601 } 602 } 603 } 604 } 605 } 606 607 /** 608 * Returns a {@code Method} object which represents the method matching the 609 * specified name and parameter types that is declared by the class 610 * represented by this {@code Class}. 611 * 612 * @param name 613 * the requested method's name. 614 * @param parameterTypes 615 * the parameter types of the requested method. 616 * {@code (Class[]) null} is equivalent to the empty array. 617 * @return the method described by {@code name} and {@code parameterTypes}. 618 * @throws NoSuchMethodException 619 * if the requested constructor cannot be found. 620 * @throws NullPointerException 621 * if {@code name} is {@code null}. 622 * @see #getMethod(String, Class[]) 623 */ getDeclaredMethod(String name, Class<?>... parameterTypes)624 public Method getDeclaredMethod(String name, Class<?>... parameterTypes) 625 throws NoSuchMethodException { 626 return getMethod(name, parameterTypes, false); 627 } 628 629 /** 630 * Returns a {@code Method} object which represents the public method with 631 * the specified name and parameter types. 632 * {@code (Class[]) null} is equivalent to the empty array. 633 * This method first searches the 634 * class C represented by this {@code Class}, then the superclasses of C and 635 * finally the interfaces implemented by C and finally the superclasses of C 636 * for a method with matching name. 637 * 638 * @throws NoSuchMethodException 639 * if the method cannot be found. 640 * @see #getDeclaredMethod(String, Class[]) 641 */ getMethod(String name, Class<?>... parameterTypes)642 public Method getMethod(String name, Class<?>... parameterTypes) throws NoSuchMethodException { 643 return getMethod(name, parameterTypes, true); 644 } 645 getMethod(String name, Class<?>[] parameterTypes, boolean recursivePublicMethods)646 private Method getMethod(String name, Class<?>[] parameterTypes, boolean recursivePublicMethods) 647 throws NoSuchMethodException { 648 if (name == null) { 649 throw new NullPointerException("name == null"); 650 } 651 if (parameterTypes == null) { 652 parameterTypes = EmptyArray.CLASS; 653 } 654 for (Class<?> c : parameterTypes) { 655 if (c == null) { 656 throw new NoSuchMethodException("parameter type is null"); 657 } 658 } 659 Method result = recursivePublicMethods ? getPublicMethodRecursive(name, parameterTypes) 660 : getDeclaredMethodInternal(name, parameterTypes); 661 // Fail if we didn't find the method or it was expected to be public. 662 if (result == null || 663 (recursivePublicMethods && !Modifier.isPublic(result.getAccessFlags()))) { 664 throw new NoSuchMethodException(name + " " + Arrays.toString(parameterTypes)); 665 } 666 return result; 667 } 668 getPublicMethodRecursive(String name, Class<?>[] parameterTypes)669 private Method getPublicMethodRecursive(String name, Class<?>[] parameterTypes) { 670 // search superclasses 671 for (Class<?> c = this; c != null; c = c.getSuperclass()) { 672 Method result = c.getDeclaredMethodInternal(name, parameterTypes); 673 if (result != null && Modifier.isPublic(result.getAccessFlags())) { 674 return result; 675 } 676 } 677 // search iftable which has a flattened and uniqued list of interfaces 678 Object[] iftable = ifTable; 679 if (iftable != null) { 680 for (int i = 0; i < iftable.length; i += 2) { 681 Class<?> ifc = (Class<?>) iftable[i]; 682 Method result = ifc.getPublicMethodRecursive(name, parameterTypes); 683 if (result != null && Modifier.isPublic(result.getAccessFlags())) { 684 return result; 685 } 686 } 687 } 688 return null; 689 } 690 691 /** 692 * Returns the method if it is defined by this class; null otherwise. This may return a 693 * non-public member. 694 * 695 * @param name the method name 696 * @param args the method's parameter types 697 */ getDeclaredMethodInternal(String name, Class<?>[] args)698 private Method getDeclaredMethodInternal(String name, Class<?>[] args) { 699 // Covariant return types permit the class to define multiple 700 // methods with the same name and parameter types. Prefer to 701 // return a non-synthetic method in such situations. We may 702 // still return a synthetic method to handle situations like 703 // escalated visibility. We never return miranda methods that 704 // were synthesized by the VM. 705 int skipModifiers = Modifier.MIRANDA | Modifier.SYNTHETIC; 706 ArtMethod artMethodResult = null; 707 if (virtualMethods != null) { 708 for (ArtMethod m : virtualMethods) { 709 String methodName = ArtMethod.getMethodName(m); 710 if (!name.equals(methodName)) { 711 continue; 712 } 713 if (!ArtMethod.equalMethodParameters(m, args)) { 714 continue; 715 } 716 int modifiers = m.getAccessFlags(); 717 if ((modifiers & skipModifiers) == 0) { 718 return new Method(m); 719 } 720 if ((modifiers & Modifier.MIRANDA) == 0) { 721 // Remember as potential result if it's not a miranda method. 722 artMethodResult = m; 723 } 724 } 725 } 726 if (artMethodResult == null) { 727 if (directMethods != null) { 728 for (ArtMethod m : directMethods) { 729 int modifiers = m.getAccessFlags(); 730 if (Modifier.isConstructor(modifiers)) { 731 continue; 732 } 733 String methodName = ArtMethod.getMethodName(m); 734 if (!name.equals(methodName)) { 735 continue; 736 } 737 if (!ArtMethod.equalMethodParameters(m, args)) { 738 continue; 739 } 740 if ((modifiers & skipModifiers) == 0) { 741 return new Method(m); 742 } 743 // Direct methods cannot be miranda methods, 744 // so this potential result must be synthetic. 745 artMethodResult = m; 746 } 747 } 748 } 749 if (artMethodResult == null) { 750 return null; 751 } 752 return new Method(artMethodResult); 753 } 754 755 /** 756 * Returns an array containing {@code Method} objects for all methods 757 * declared in the class represented by this {@code Class}. If there are no 758 * methods or if this {@code Class} represents an array class, a primitive 759 * type or void then an empty array is returned. 760 * 761 * @see #getMethods() 762 */ getDeclaredMethods()763 public Method[] getDeclaredMethods() { 764 int initial_size = virtualMethods == null ? 0 : virtualMethods.length; 765 initial_size += directMethods == null ? 0 : directMethods.length; 766 ArrayList<Method> methods = new ArrayList<Method>(initial_size); 767 getDeclaredMethods(false, methods); 768 Method[] result = methods.toArray(new Method[methods.size()]); 769 for (Method m : result) { 770 // Throw NoClassDefFoundError if types cannot be resolved. 771 m.getReturnType(); 772 m.getParameterTypes(); 773 } 774 return result; 775 776 } 777 778 /** 779 * Returns the list of methods without performing any security checks 780 * first. If no methods exist, an empty array is returned. 781 */ getDeclaredMethods(boolean publicOnly, List<Method> methods)782 private void getDeclaredMethods(boolean publicOnly, List<Method> methods) { 783 if (virtualMethods != null) { 784 for (ArtMethod m : virtualMethods) { 785 int modifiers = m.getAccessFlags(); 786 if (!publicOnly || Modifier.isPublic(modifiers)) { 787 // Add non-miranda virtual methods. 788 if ((modifiers & Modifier.MIRANDA) == 0) { 789 methods.add(new Method(m)); 790 } 791 } 792 } 793 } 794 if (directMethods != null) { 795 for (ArtMethod m : directMethods) { 796 int modifiers = m.getAccessFlags(); 797 if (!publicOnly || Modifier.isPublic(modifiers)) { 798 // Add non-constructor direct/static methods. 799 if (!Modifier.isConstructor(modifiers)) { 800 methods.add(new Method(m)); 801 } 802 } 803 } 804 } 805 } 806 807 /** 808 * Returns an array containing {@code Method} objects for all public methods 809 * for the class C represented by this {@code Class}. Methods may be 810 * declared in C, the interfaces it implements or in the superclasses of C. 811 * The elements in the returned array are in no particular order. 812 * 813 * <p>If there are no public methods or if this {@code Class} represents a 814 * primitive type or {@code void} then an empty array is returned. 815 * 816 * @see #getDeclaredMethods() 817 */ getMethods()818 public Method[] getMethods() { 819 List<Method> methods = new ArrayList<Method>(); 820 getPublicMethodsInternal(methods); 821 /* 822 * Remove duplicate methods defined by superclasses and 823 * interfaces, preferring to keep methods declared by derived 824 * types. 825 */ 826 CollectionUtils.removeDuplicates(methods, Method.ORDER_BY_SIGNATURE); 827 return methods.toArray(new Method[methods.size()]); 828 } 829 830 /** 831 * Populates {@code result} with public methods defined by this class, its 832 * superclasses, and all implemented interfaces, including overridden methods. 833 */ getPublicMethodsInternal(List<Method> result)834 private void getPublicMethodsInternal(List<Method> result) { 835 getDeclaredMethods(true, result); 836 if (!isInterface()) { 837 // Search superclasses, for interfaces don't search java.lang.Object. 838 for (Class<?> c = superClass; c != null; c = c.superClass) { 839 c.getDeclaredMethods(true, result); 840 } 841 } 842 // Search iftable which has a flattened and uniqued list of interfaces. 843 Object[] iftable = ifTable; 844 if (iftable != null) { 845 for (int i = 0; i < iftable.length; i += 2) { 846 Class<?> ifc = (Class<?>) iftable[i]; 847 ifc.getDeclaredMethods(true, result); 848 } 849 } 850 } 851 852 /** 853 * Returns the annotations that are directly defined on the class 854 * represented by this {@code Class}. Annotations that are inherited are not 855 * included in the result. If there are no annotations at all, an empty 856 * array is returned. 857 * 858 * @see #getAnnotations() 859 */ getDeclaredAnnotations()860 @Override public Annotation[] getDeclaredAnnotations() { 861 List<Annotation> result = AnnotationAccess.getDeclaredAnnotations(this); 862 return result.toArray(new Annotation[result.size()]); 863 } 864 865 /** 866 * Returns an array containing {@code Class} objects for all classes, 867 * interfaces, enums and annotations that are members of this class. 868 */ getDeclaredClasses()869 public Class<?>[] getDeclaredClasses() { 870 return AnnotationAccess.getMemberClasses(this); 871 } 872 873 /** 874 * Returns a {@code Field} object for the field with the given name 875 * which is declared in the class represented by this {@code Class}. 876 * 877 * @throws NoSuchFieldException if the requested field can not be found. 878 * @see #getField(String) 879 */ getDeclaredField(String name)880 public Field getDeclaredField(String name) throws NoSuchFieldException { 881 if (name == null) { 882 throw new NullPointerException("name == null"); 883 } 884 Field result = getDeclaredFieldInternal(name); 885 if (result == null) { 886 throw new NoSuchFieldException(name); 887 } else { 888 result.getType(); // Throw NoClassDefFoundError if type cannot be resolved. 889 } 890 return result; 891 } 892 893 /** 894 * Returns an array containing {@code Field} objects for all fields declared 895 * in the class represented by this {@code Class}. If there are no fields or 896 * if this {@code Class} represents an array class, a primitive type or void 897 * then an empty array is returned. 898 * 899 * @see #getFields() 900 */ getDeclaredFields()901 public Field[] getDeclaredFields() { 902 int initial_size = sFields == null ? 0 : sFields.length; 903 initial_size += iFields == null ? 0 : iFields.length; 904 ArrayList<Field> fields = new ArrayList(initial_size); 905 getDeclaredFields(false, fields); 906 Field[] result = fields.toArray(new Field[fields.size()]); 907 for (Field f : result) { 908 f.getType(); // Throw NoClassDefFoundError if type cannot be resolved. 909 } 910 return result; 911 } 912 getDeclaredFields(boolean publicOnly, List<Field> fields)913 private void getDeclaredFields(boolean publicOnly, List<Field> fields) { 914 if (iFields != null) { 915 for (ArtField f : iFields) { 916 if (!publicOnly || Modifier.isPublic(f.getAccessFlags())) { 917 fields.add(new Field(f)); 918 } 919 } 920 } 921 if (sFields != null) { 922 for (ArtField f : sFields) { 923 if (!publicOnly || Modifier.isPublic(f.getAccessFlags())) { 924 fields.add(new Field(f)); 925 } 926 } 927 } 928 } 929 930 /** 931 * Returns the field if it is defined by this class; null otherwise. This 932 * may return a non-public member. 933 */ getDeclaredFieldInternal(String name)934 private Field getDeclaredFieldInternal(String name) { 935 if (iFields != null) { 936 for (ArtField f : iFields) { 937 if (f.getName().equals(name)) { 938 return new Field(f); 939 } 940 } 941 } 942 if (sFields != null) { 943 for (ArtField f : sFields) { 944 if (f.getName().equals(name)) { 945 return new Field(f); 946 } 947 } 948 } 949 return null; 950 } 951 952 /** 953 * Returns the class that this class is a member of, or {@code null} if this 954 * class is a top-level class, a primitive, an array, or defined within a 955 * method or constructor. 956 */ getDeclaringClass()957 public Class<?> getDeclaringClass() { 958 if (AnnotationAccess.isAnonymousClass(this)) { 959 return null; 960 } 961 return AnnotationAccess.getEnclosingClass(this); 962 } 963 964 /** 965 * Returns the class enclosing this class. For most classes this is the same 966 * as the {@link #getDeclaringClass() declaring class}. For classes defined 967 * within a method or constructor (typically anonymous inner classes), this 968 * is the declaring class of that member. 969 */ getEnclosingClass()970 public Class<?> getEnclosingClass() { 971 Class<?> declaringClass = getDeclaringClass(); 972 if (declaringClass != null) { 973 return declaringClass; 974 } 975 AccessibleObject member = AnnotationAccess.getEnclosingMethodOrConstructor(this); 976 if (member != null) { 977 return ((Member) member).getDeclaringClass(); 978 } 979 return AnnotationAccess.getEnclosingClass(this); 980 } 981 982 /** 983 * Returns the enclosing {@code Constructor} of this {@code Class}, if it is an 984 * anonymous or local/automatic class; otherwise {@code null}. 985 */ getEnclosingConstructor()986 public Constructor<?> getEnclosingConstructor() { 987 if (classNameImpliesTopLevel()) { 988 return null; 989 } 990 AccessibleObject result = AnnotationAccess.getEnclosingMethodOrConstructor(this); 991 return result instanceof Constructor ? (Constructor<?>) result : null; 992 } 993 994 /** 995 * Returns the enclosing {@code Method} of this {@code Class}, if it is an 996 * anonymous or local/automatic class; otherwise {@code null}. 997 */ getEnclosingMethod()998 public Method getEnclosingMethod() { 999 if (classNameImpliesTopLevel()) { 1000 return null; 1001 } 1002 AccessibleObject result = AnnotationAccess.getEnclosingMethodOrConstructor(this); 1003 return result instanceof Method ? (Method) result : null; 1004 } 1005 1006 /** 1007 * Returns true if this class is definitely a top level class, or false if 1008 * a more expensive check like {@link #getEnclosingClass()} is necessary. 1009 * 1010 * <p>This is a hack that exploits an implementation detail of all Java 1011 * language compilers: generated names always contain "$". As it is possible 1012 * for a top level class to be named with a "$", a false result <strong>does 1013 * not</strong> indicate that this isn't a top-level class. 1014 */ classNameImpliesTopLevel()1015 private boolean classNameImpliesTopLevel() { 1016 return !getName().contains("$"); 1017 } 1018 1019 /** 1020 * Returns the {@code enum} constants associated with this {@code Class}. 1021 * Returns {@code null} if this {@code Class} does not represent an {@code 1022 * enum} type. 1023 */ 1024 @SuppressWarnings("unchecked") // we only cast after confirming that this class is an enum getEnumConstants()1025 public T[] getEnumConstants() { 1026 if (!isEnum()) { 1027 return null; 1028 } 1029 return (T[]) Enum.getSharedConstants((Class) this).clone(); 1030 } 1031 1032 /** 1033 * Returns a {@code Field} object which represents the public field with the 1034 * given name. This method first searches the class C represented by 1035 * this {@code Class}, then the interfaces implemented by C and finally the 1036 * superclasses of C. 1037 * 1038 * @throws NoSuchFieldException 1039 * if the field cannot be found. 1040 * @see #getDeclaredField(String) 1041 */ getField(String name)1042 public Field getField(String name) throws NoSuchFieldException { 1043 if (name == null) { 1044 throw new NullPointerException("name == null"); 1045 } 1046 Field result = getPublicFieldRecursive(name); 1047 if (result == null) { 1048 throw new NoSuchFieldException(name); 1049 } else { 1050 result.getType(); // Throw NoClassDefFoundError if type cannot be resolved. 1051 } 1052 return result; 1053 } 1054 getPublicFieldRecursive(String name)1055 private Field getPublicFieldRecursive(String name) { 1056 // search superclasses 1057 for (Class<?> c = this; c != null; c = c.superClass) { 1058 Field result = c.getDeclaredFieldInternal(name); 1059 if (result != null && (result.getModifiers() & Modifier.PUBLIC) != 0) { 1060 return result; 1061 } 1062 } 1063 1064 // search iftable which has a flattened and uniqued list of interfaces 1065 if (ifTable != null) { 1066 for (int i = 0; i < ifTable.length; i += 2) { 1067 Class<?> ifc = (Class<?>) ifTable[i]; 1068 Field result = ifc.getPublicFieldRecursive(name); 1069 if (result != null && (result.getModifiers() & Modifier.PUBLIC) != 0) { 1070 return result; 1071 } 1072 } 1073 } 1074 1075 return null; 1076 } 1077 1078 /** 1079 * Returns an array containing {@code Field} objects for all public fields 1080 * for the class C represented by this {@code Class}. Fields may be declared 1081 * in C, the interfaces it implements or in the superclasses of C. The 1082 * elements in the returned array are in no particular order. 1083 * 1084 * <p>If there are no public fields or if this class represents an array class, 1085 * a primitive type or {@code void} then an empty array is returned. 1086 * 1087 * @see #getDeclaredFields() 1088 */ getFields()1089 public Field[] getFields() { 1090 List<Field> fields = new ArrayList<Field>(); 1091 getPublicFieldsRecursive(fields); 1092 Field[] result = fields.toArray(new Field[fields.size()]); 1093 for (Field f : result) { 1094 f.getType(); // Throw NoClassDefFoundError if type cannot be resolved. 1095 } 1096 return result; 1097 } 1098 1099 /** 1100 * Populates {@code result} with public fields defined by this class, its 1101 * superclasses, and all implemented interfaces. 1102 */ getPublicFieldsRecursive(List<Field> result)1103 private void getPublicFieldsRecursive(List<Field> result) { 1104 // search superclasses 1105 for (Class<?> c = this; c != null; c = c.superClass) { 1106 c.getDeclaredFields(true, result); 1107 } 1108 1109 // search iftable which has a flattened and uniqued list of interfaces 1110 Object[] iftable = ifTable; 1111 if (iftable != null) { 1112 for (int i = 0; i < iftable.length; i += 2) { 1113 Class<?> ifc = (Class<?>) iftable[i]; 1114 ifc.getDeclaredFields(true, result); 1115 } 1116 } 1117 } 1118 1119 /** 1120 * Returns the {@link Type}s of the interfaces that this {@code Class} directly 1121 * implements. If the {@code Class} represents a primitive type or {@code 1122 * void} then an empty array is returned. 1123 */ getGenericInterfaces()1124 public Type[] getGenericInterfaces() { 1125 Type[] result; 1126 synchronized (Caches.genericInterfaces) { 1127 result = Caches.genericInterfaces.get(this); 1128 if (result == null) { 1129 String annotationSignature = AnnotationAccess.getSignature(this); 1130 if (annotationSignature == null) { 1131 result = getInterfaces(); 1132 } else { 1133 GenericSignatureParser parser = new GenericSignatureParser(getClassLoader()); 1134 parser.parseForClass(this, annotationSignature); 1135 result = Types.getTypeArray(parser.interfaceTypes, false); 1136 } 1137 Caches.genericInterfaces.put(this, result); 1138 } 1139 } 1140 return (result.length == 0) ? result : result.clone(); 1141 } 1142 1143 /** 1144 * Returns the {@code Type} that represents the superclass of this {@code 1145 * class}. 1146 */ getGenericSuperclass()1147 public Type getGenericSuperclass() { 1148 Type genericSuperclass = getSuperclass(); 1149 // This method is specified to return null for all cases where getSuperclass 1150 // returns null, i.e, for primitives, interfaces, void and java.lang.Object. 1151 if (genericSuperclass == null) { 1152 return null; 1153 } 1154 1155 String annotationSignature = AnnotationAccess.getSignature(this); 1156 if (annotationSignature != null) { 1157 GenericSignatureParser parser = new GenericSignatureParser(getClassLoader()); 1158 parser.parseForClass(this, annotationSignature); 1159 genericSuperclass = parser.superclassType; 1160 } 1161 return Types.getType(genericSuperclass); 1162 } 1163 1164 /** 1165 * Returns an array of {@code Class} objects that match the interfaces 1166 * in the {@code implements} declaration of the class represented 1167 * by this {@code Class}. The order of the elements in the array is 1168 * identical to the order in the original class declaration. If the class 1169 * does not implement any interfaces, an empty array is returned. 1170 * 1171 * <p>This method only returns directly-implemented interfaces, and does not 1172 * include interfaces implemented by superclasses or superinterfaces of any 1173 * implemented interfaces. 1174 */ getInterfaces()1175 public Class<?>[] getInterfaces() { 1176 if (isArray()) { 1177 return new Class<?>[] { Cloneable.class, Serializable.class }; 1178 } else if (isProxy()) { 1179 return getProxyInterfaces(); 1180 } 1181 Dex dex = getDex(); 1182 if (dex == null) { 1183 return EmptyArray.CLASS; 1184 } 1185 short[] interfaces = dex.interfaceTypeIndicesFromClassDefIndex(dexClassDefIndex); 1186 Class<?>[] result = new Class<?>[interfaces.length]; 1187 for (int i = 0; i < interfaces.length; i++) { 1188 result[i] = getDexCacheType(dex, interfaces[i]); 1189 } 1190 return result; 1191 } 1192 1193 // Returns the interfaces that this proxy class directly implements. getProxyInterfaces()1194 private native Class<?>[] getProxyInterfaces(); 1195 1196 /** 1197 * Returns an integer that represents the modifiers of the class represented 1198 * by this {@code Class}. The returned value is a combination of bits 1199 * defined by constants in the {@link Modifier} class. 1200 */ getModifiers()1201 public int getModifiers() { 1202 // Array classes inherit modifiers from their component types, but in the case of arrays 1203 // of an inner class, the class file may contain "fake" access flags because it's not valid 1204 // for a top-level class to private, say. The real access flags are stored in the InnerClass 1205 // attribute, so we need to make sure we drill down to the inner class: the accessFlags 1206 // field is not the value we want to return, and the synthesized array class does not itself 1207 // have an InnerClass attribute. https://code.google.com/p/android/issues/detail?id=56267 1208 if (isArray()) { 1209 int componentModifiers = getComponentType().getModifiers(); 1210 if ((componentModifiers & Modifier.INTERFACE) != 0) { 1211 componentModifiers &= ~(Modifier.INTERFACE | Modifier.STATIC); 1212 } 1213 return Modifier.ABSTRACT | Modifier.FINAL | componentModifiers; 1214 } 1215 int JAVA_FLAGS_MASK = 0xffff; 1216 int modifiers = AnnotationAccess.getInnerClassFlags(this, accessFlags & JAVA_FLAGS_MASK); 1217 return modifiers & JAVA_FLAGS_MASK; 1218 } 1219 1220 /** 1221 * Returns the name of the class represented by this {@code Class}. For a 1222 * description of the format which is used, see the class definition of 1223 * {@link Class}. 1224 */ getName()1225 public String getName() { 1226 String result = name; 1227 return (result == null) ? (name = getNameNative()) : result; 1228 } 1229 getNameNative()1230 private native String getNameNative(); 1231 1232 /** 1233 * Returns the simple name of the class represented by this {@code Class} as 1234 * defined in the source code. If there is no name (that is, the class is 1235 * anonymous) then an empty string is returned. If the receiver is an array 1236 * then the name of the underlying type with square braces appended (for 1237 * example {@code "Integer[]"}) is returned. 1238 * 1239 * @return the simple name of the class represented by this {@code Class}. 1240 */ getSimpleName()1241 public String getSimpleName() { 1242 if (isArray()) { 1243 return getComponentType().getSimpleName() + "[]"; 1244 } 1245 1246 if (isAnonymousClass()) { 1247 return ""; 1248 } 1249 1250 if (isMemberClass() || isLocalClass()) { 1251 return getInnerClassName(); 1252 } 1253 1254 String name = getName(); 1255 int dot = name.lastIndexOf('.'); 1256 if (dot != -1) { 1257 return name.substring(dot + 1); 1258 } 1259 1260 return name; 1261 } 1262 1263 /** 1264 * Returns the simple name of a member or local class, or null otherwise. 1265 */ getInnerClassName()1266 private String getInnerClassName() { 1267 return AnnotationAccess.getInnerClassName(this); 1268 } 1269 1270 /** 1271 * Returns null. 1272 */ getProtectionDomain()1273 public ProtectionDomain getProtectionDomain() { 1274 return null; 1275 } 1276 1277 /** 1278 * Returns the URL of the given resource, or null if the resource is not found. 1279 * The mapping between the resource name and the URL is managed by the class' class loader. 1280 * 1281 * @see ClassLoader 1282 */ getResource(String resourceName)1283 public URL getResource(String resourceName) { 1284 // Get absolute resource name, but without the leading slash 1285 if (resourceName.startsWith("/")) { 1286 resourceName = resourceName.substring(1); 1287 } else { 1288 String pkg = getName(); 1289 int dot = pkg.lastIndexOf('.'); 1290 if (dot != -1) { 1291 pkg = pkg.substring(0, dot).replace('.', '/'); 1292 } else { 1293 pkg = ""; 1294 } 1295 1296 resourceName = pkg + "/" + resourceName; 1297 } 1298 1299 // Delegate to proper class loader 1300 ClassLoader loader = getClassLoader(); 1301 if (loader != null) { 1302 return loader.getResource(resourceName); 1303 } else { 1304 return ClassLoader.getSystemResource(resourceName); 1305 } 1306 } 1307 1308 /** 1309 * Returns a read-only stream for the contents of the given resource, or null if the resource 1310 * is not found. 1311 * The mapping between the resource name and the stream is managed by the class' class loader. 1312 * 1313 * @see ClassLoader 1314 */ getResourceAsStream(String resourceName)1315 public InputStream getResourceAsStream(String resourceName) { 1316 // Get absolute resource name, but without the leading slash 1317 if (resourceName.startsWith("/")) { 1318 resourceName = resourceName.substring(1); 1319 } else { 1320 String pkg = getName(); 1321 int dot = pkg.lastIndexOf('.'); 1322 if (dot != -1) { 1323 pkg = pkg.substring(0, dot).replace('.', '/'); 1324 } else { 1325 pkg = ""; 1326 } 1327 1328 resourceName = pkg + "/" + resourceName; 1329 } 1330 1331 // Delegate to proper class loader 1332 ClassLoader loader = getClassLoader(); 1333 if (loader != null) { 1334 return loader.getResourceAsStream(resourceName); 1335 } else { 1336 return ClassLoader.getSystemResourceAsStream(resourceName); 1337 } 1338 } 1339 1340 /** 1341 * Returns null. (On Android, a {@code ClassLoader} can load classes from multiple dex files. 1342 * All classes from any given dex file will have the same signers, but different dex 1343 * files may have different signers. This does not fit well with the original 1344 * {@code ClassLoader}-based model of {@code getSigners}.) 1345 */ getSigners()1346 public Object[] getSigners() { 1347 // See http://code.google.com/p/android/issues/detail?id=1766. 1348 return null; 1349 } 1350 1351 /** 1352 * Returns the {@code Class} object which represents the superclass of the 1353 * class represented by this {@code Class}. If this {@code Class} represents 1354 * the {@code Object} class, a primitive type, an interface or void then the 1355 * method returns {@code null}. If this {@code Class} represents an array 1356 * class then the {@code Object} class is returned. 1357 */ getSuperclass()1358 public Class<? super T> getSuperclass() { 1359 // For interfaces superClass is Object (which agrees with the JNI spec) 1360 // but not with the expected behavior here. 1361 if (isInterface()) { 1362 return null; 1363 } else { 1364 return superClass; 1365 } 1366 } 1367 1368 /** 1369 * Returns an array containing {@code TypeVariable} objects for type 1370 * variables declared by the generic class represented by this {@code 1371 * Class}. Returns an empty array if the class is not generic. 1372 */ 1373 @SuppressWarnings("unchecked") getTypeParameters()1374 @Override public synchronized TypeVariable<Class<T>>[] getTypeParameters() { 1375 String annotationSignature = AnnotationAccess.getSignature(this); 1376 if (annotationSignature == null) { 1377 return EmptyArray.TYPE_VARIABLE; 1378 } 1379 GenericSignatureParser parser = new GenericSignatureParser(getClassLoader()); 1380 parser.parseForClass(this, annotationSignature); 1381 return parser.formalTypeParameters; 1382 } 1383 1384 /** 1385 * Tests whether this {@code Class} represents an annotation class. 1386 */ isAnnotation()1387 public boolean isAnnotation() { 1388 final int ACC_ANNOTATION = 0x2000; // not public in reflect.Modifier 1389 return (accessFlags & ACC_ANNOTATION) != 0; 1390 } 1391 isAnnotationPresent(Class<? extends Annotation> annotationType)1392 @Override public boolean isAnnotationPresent(Class<? extends Annotation> annotationType) { 1393 return AnnotationAccess.isAnnotationPresent(this, annotationType); 1394 } 1395 1396 /** 1397 * Tests whether the class represented by this {@code Class} is 1398 * anonymous. 1399 */ isAnonymousClass()1400 public boolean isAnonymousClass() { 1401 return AnnotationAccess.isAnonymousClass(this); 1402 } 1403 1404 /** 1405 * Tests whether the class represented by this {@code Class} is an array class. 1406 */ isArray()1407 public boolean isArray() { 1408 return getComponentType() != null; 1409 } 1410 1411 /** 1412 * Is this a runtime created proxy class? 1413 * 1414 * @hide 1415 */ isProxy()1416 public boolean isProxy() { 1417 return (accessFlags & 0x00040000) != 0; 1418 } 1419 1420 /** 1421 * Can {@code c} be assigned to this class? For example, String can be assigned to Object 1422 * (by an upcast), however, an Object cannot be assigned to a String as a potentially exception 1423 * throwing downcast would be necessary. Similarly for interfaces, a class that implements (or 1424 * an interface that extends) another can be assigned to its parent, but not vice-versa. All 1425 * Classes may assign to themselves. Classes for primitive types may not assign to each other. 1426 * 1427 * @param c the class to check. 1428 * @return {@code true} if {@code c} can be assigned to the class 1429 * represented by this {@code Class}; {@code false} otherwise. 1430 * @throws NullPointerException if {@code c} is {@code null}. 1431 */ isAssignableFrom(Class<?> c)1432 public boolean isAssignableFrom(Class<?> c) { 1433 if (this == c) { 1434 return true; // Can always assign to things of the same type. 1435 } else if (this == Object.class) { 1436 return !c.isPrimitive(); // Can assign any reference to java.lang.Object. 1437 } else if (isArray()) { 1438 return c.isArray() && componentType.isAssignableFrom(c.componentType); 1439 } else if (isInterface()) { 1440 // Search iftable which has a flattened and uniqued list of interfaces. 1441 Object[] iftable = c.ifTable; 1442 if (iftable != null) { 1443 for (int i = 0; i < iftable.length; i += 2) { 1444 Class<?> ifc = (Class<?>) iftable[i]; 1445 if (ifc == this) { 1446 return true; 1447 } 1448 } 1449 } 1450 return false; 1451 } else { 1452 if (!c.isInterface()) { 1453 for (c = c.superClass; c != null; c = c.superClass) { 1454 if (c == this) { 1455 return true; 1456 } 1457 } 1458 } 1459 return false; 1460 } 1461 } 1462 1463 /** 1464 * Tests whether the class represented by this {@code Class} is an 1465 * {@code enum}. 1466 */ isEnum()1467 public boolean isEnum() { 1468 return (getSuperclass() == Enum.class) && ((accessFlags & 0x4000) != 0); 1469 } 1470 1471 /** 1472 * Tests whether the given object can be cast to the class 1473 * represented by this {@code Class}. This is the runtime version of the 1474 * {@code instanceof} operator. 1475 * 1476 * @return {@code true} if {@code object} can be cast to the type 1477 * represented by this {@code Class}; {@code false} if {@code 1478 * object} is {@code null} or cannot be cast. 1479 */ isInstance(Object object)1480 public boolean isInstance(Object object) { 1481 if (object == null) { 1482 return false; 1483 } 1484 return isAssignableFrom(object.getClass()); 1485 } 1486 1487 /** 1488 * Tests whether this {@code Class} represents an interface. 1489 */ isInterface()1490 public boolean isInterface() { 1491 return (accessFlags & Modifier.INTERFACE) != 0; 1492 } 1493 1494 /** 1495 * Tests whether the class represented by this {@code Class} is defined 1496 * locally. 1497 */ isLocalClass()1498 public boolean isLocalClass() { 1499 return !classNameImpliesTopLevel() 1500 && AnnotationAccess.getEnclosingMethodOrConstructor(this) != null 1501 && !isAnonymousClass(); 1502 } 1503 1504 /** 1505 * Tests whether the class represented by this {@code Class} is a member 1506 * class. 1507 */ isMemberClass()1508 public boolean isMemberClass() { 1509 return getDeclaringClass() != null; 1510 } 1511 1512 /** 1513 * Tests whether this {@code Class} represents a primitive type. 1514 */ isPrimitive()1515 public boolean isPrimitive() { 1516 return primitiveType != 0; 1517 } 1518 1519 /** 1520 * Tests whether this {@code Class} represents a synthetic type. 1521 */ isSynthetic()1522 public boolean isSynthetic() { 1523 final int ACC_SYNTHETIC = 0x1000; // not public in reflect.Modifier 1524 return (accessFlags & ACC_SYNTHETIC) != 0; 1525 } 1526 1527 /** 1528 * Indicates whether this {@code Class} or its parents override finalize. 1529 * 1530 * @hide 1531 */ isFinalizable()1532 public boolean isFinalizable() { 1533 final int ACC_CLASS_IS_FINALIZABLE = 0x80000000; // not public in reflect.Modifier 1534 return (accessFlags & ACC_CLASS_IS_FINALIZABLE) != 0; 1535 } 1536 1537 /** 1538 * Returns a new instance of the class represented by this {@code Class}, 1539 * created by invoking the default (that is, zero-argument) constructor. If 1540 * there is no such constructor, or if the creation fails (either because of 1541 * a lack of available memory or because an exception is thrown by the 1542 * constructor), an {@code InstantiationException} is thrown. If the default 1543 * constructor exists but is not accessible from the context where this 1544 * method is invoked, an {@code IllegalAccessException} is thrown. 1545 * 1546 * @throws IllegalAccessException 1547 * if the default constructor is not visible. 1548 * @throws InstantiationException 1549 * if the instance cannot be created. 1550 */ newInstance()1551 public T newInstance() throws InstantiationException, IllegalAccessException { 1552 if (isPrimitive() || isInterface() || isArray() || Modifier.isAbstract(accessFlags)) { 1553 throw new InstantiationException(this + " cannot be instantiated"); 1554 } 1555 Class<?> caller = VMStack.getStackClass1(); 1556 if (!caller.canAccess(this)) { 1557 throw new IllegalAccessException(this + " is not accessible from " + caller); 1558 } 1559 Constructor<T> init; 1560 try { 1561 init = getDeclaredConstructor(); 1562 } catch (NoSuchMethodException e) { 1563 InstantiationException t = 1564 new InstantiationException(this + " has no zero argument constructor"); 1565 t.initCause(e); 1566 throw t; 1567 } 1568 if (!caller.canAccessMember(this, init.getAccessFlags())) { 1569 throw new IllegalAccessException(init + " is not accessible from " + caller); 1570 } 1571 try { 1572 return init.newInstance(null, init.isAccessible()); 1573 } catch (InvocationTargetException e) { 1574 SneakyThrow.sneakyThrow(e.getCause()); 1575 return null; // Unreachable. 1576 } 1577 } 1578 canAccess(Class<?> c)1579 private boolean canAccess(Class<?> c) { 1580 if(Modifier.isPublic(c.accessFlags)) { 1581 return true; 1582 } 1583 return inSamePackage(c); 1584 } 1585 canAccessMember(Class<?> memberClass, int memberModifiers)1586 private boolean canAccessMember(Class<?> memberClass, int memberModifiers) { 1587 if (memberClass == this || Modifier.isPublic(memberModifiers)) { 1588 return true; 1589 } 1590 if (Modifier.isPrivate(memberModifiers)) { 1591 return false; 1592 } 1593 if (Modifier.isProtected(memberModifiers)) { 1594 for (Class<?> parent = this.superClass; parent != null; parent = parent.superClass) { 1595 if (parent == memberClass) { 1596 return true; 1597 } 1598 } 1599 } 1600 return inSamePackage(memberClass); 1601 } 1602 inSamePackage(Class<?> c)1603 private boolean inSamePackage(Class<?> c) { 1604 if (classLoader != c.classLoader) { 1605 return false; 1606 } 1607 String packageName1 = getPackageName$(); 1608 String packageName2 = c.getPackageName$(); 1609 if (packageName1 == null) { 1610 return packageName2 == null; 1611 } else if (packageName2 == null) { 1612 return false; 1613 } else { 1614 return packageName1.equals(packageName2); 1615 } 1616 } 1617 1618 @Override toString()1619 public String toString() { 1620 if (isPrimitive()) { 1621 return getSimpleName(); 1622 } else { 1623 return (isInterface() ? "interface " : "class ") + getName(); 1624 } 1625 } 1626 1627 /** 1628 * Returns the {@code Package} of which the class represented by this 1629 * {@code Class} is a member. Returns {@code null} if no {@code Package} 1630 * object was created by the class loader of the class. 1631 */ getPackage()1632 public Package getPackage() { 1633 // TODO This might be a hack, but the VM doesn't have the necessary info. 1634 ClassLoader loader = getClassLoader(); 1635 if (loader != null) { 1636 String packageName = getPackageName$(); 1637 return packageName != null ? loader.getPackage(packageName) : null; 1638 } 1639 return null; 1640 } 1641 1642 /** 1643 * Returns the package name of this class. This returns null for classes in 1644 * the default package. 1645 * 1646 * @hide 1647 */ getPackageName$()1648 public String getPackageName$() { 1649 String name = getName(); 1650 int last = name.lastIndexOf('.'); 1651 return last == -1 ? null : name.substring(0, last); 1652 } 1653 1654 /** 1655 * Returns the assertion status for the class represented by this {@code 1656 * Class}. Assertion is enabled / disabled based on the class loader, 1657 * package or class default at runtime. 1658 */ desiredAssertionStatus()1659 public boolean desiredAssertionStatus() { 1660 return false; 1661 } 1662 1663 /** 1664 * Casts this {@code Class} to represent a subclass of the given class. 1665 * If successful, this {@code Class} is returned; otherwise a {@code 1666 * ClassCastException} is thrown. 1667 * 1668 * @throws ClassCastException 1669 * if this {@code Class} cannot be cast to the given type. 1670 */ 1671 @SuppressWarnings("unchecked") asSubclass(Class<U> c)1672 public <U> Class<? extends U> asSubclass(Class<U> c) { 1673 if (c.isAssignableFrom(this)) { 1674 return (Class<? extends U>)this; 1675 } 1676 String actualClassName = this.getName(); 1677 String desiredClassName = c.getName(); 1678 throw new ClassCastException(actualClassName + " cannot be cast to " + desiredClassName); 1679 } 1680 1681 /** 1682 * Casts the given object to the type represented by this {@code Class}. 1683 * If the object is {@code null} then the result is also {@code null}. 1684 * 1685 * @throws ClassCastException 1686 * if the object cannot be cast to the given type. 1687 */ 1688 @SuppressWarnings("unchecked") cast(Object obj)1689 public T cast(Object obj) { 1690 if (obj == null) { 1691 return null; 1692 } else if (this.isInstance(obj)) { 1693 return (T)obj; 1694 } 1695 String actualClassName = obj.getClass().getName(); 1696 String desiredClassName = this.getName(); 1697 throw new ClassCastException(actualClassName + " cannot be cast to " + desiredClassName); 1698 } 1699 1700 /** 1701 * The class def of this class in its own Dex, or -1 if there is no class def. 1702 * 1703 * @hide 1704 */ getDexClassDefIndex()1705 public int getDexClassDefIndex() { 1706 return (dexClassDefIndex == 65535) ? -1 : dexClassDefIndex; 1707 } 1708 1709 /** 1710 * The type index of this class in its own Dex, or -1 if it is unknown. If a class is referenced 1711 * by multiple Dex files, it will have a different type index in each. Dex files support 65534 1712 * type indices, with 65535 representing no index. 1713 * 1714 * @hide 1715 */ getDexTypeIndex()1716 public int getDexTypeIndex() { 1717 int typeIndex = dexTypeIndex; 1718 if (typeIndex != 65535) { 1719 return typeIndex; 1720 } 1721 synchronized (this) { 1722 typeIndex = dexTypeIndex; 1723 if (typeIndex == 65535) { 1724 if (dexClassDefIndex >= 0) { 1725 typeIndex = getDex().typeIndexFromClassDefIndex(dexClassDefIndex); 1726 } else { 1727 typeIndex = getDex().findTypeIndex(InternalNames.getInternalName(this)); 1728 if (typeIndex < 0) { 1729 typeIndex = -1; 1730 } 1731 } 1732 dexTypeIndex = typeIndex; 1733 } 1734 } 1735 return typeIndex; 1736 } 1737 1738 /** 1739 * The annotation directory offset of this class in its own Dex, or 0 if it 1740 * is unknown. 1741 * 1742 * TODO: 0 is a sentinel that means 'no annotations directory'; this should be -1 if unknown 1743 * 1744 * @hide 1745 */ getDexAnnotationDirectoryOffset()1746 public int getDexAnnotationDirectoryOffset() { 1747 Dex dex = getDex(); 1748 if (dex == null) { 1749 return 0; 1750 } 1751 int classDefIndex = getDexClassDefIndex(); 1752 if (classDefIndex < 0) { 1753 return 0; 1754 } 1755 return dex.annotationDirectoryOffsetFromClassDefIndex(classDefIndex); 1756 } 1757 1758 private static class Caches { 1759 /** 1760 * Cache to avoid frequent recalculation of generic interfaces, which is generally uncommon. 1761 * Sized sufficient to allow ConcurrentHashMapTest to run without recalculating its generic 1762 * interfaces (required to avoid time outs). Validated by running reflection heavy code 1763 * such as applications using Guice-like frameworks. 1764 */ 1765 private static final BasicLruCache<Class, Type[]> genericInterfaces 1766 = new BasicLruCache<Class, Type[]>(8); 1767 } 1768 } 1769