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.nio.charset.StandardCharsets; 55 import java.security.ProtectionDomain; 56 import java.util.ArrayList; 57 import java.util.Arrays; 58 import java.util.List; 59 import libcore.reflect.AnnotationAccess; 60 import libcore.reflect.GenericSignatureParser; 61 import libcore.reflect.InternalNames; 62 import libcore.reflect.Types; 63 import libcore.util.BasicLruCache; 64 import libcore.util.CollectionUtils; 65 import libcore.util.EmptyArray; 66 import libcore.util.SneakyThrow; 67 68 /** 69 * The in-memory representation of a Java class. This representation serves as 70 * the starting point for querying class-related information, a process usually 71 * called "reflection". There are basically three types of {@code Class} 72 * instances: those representing real classes and interfaces, those representing 73 * primitive types, and those representing array classes. 74 * 75 * <h4>Class instances representing object types (classes or interfaces)</h4> 76 * <p> 77 * These represent an ordinary class or interface as found in the class 78 * hierarchy. The name associated with these {@code Class} instances is simply 79 * the fully qualified class name of the class or interface that it represents. 80 * In addition to this human-readable name, each class is also associated by a 81 * so-called <em>descriptor</em>, which is the letter "L", followed by the 82 * class name and a semicolon (";"). The descriptor is what the runtime system 83 * uses internally for identifying the class (for example in a DEX file). 84 * </p> 85 * <h4>Classes representing primitive types</h4> 86 * <p> 87 * These represent the standard Java primitive types and hence share their 88 * names (for example "int" for the {@code int} primitive type). Although it is 89 * not possible to create new instances based on these {@code Class} instances, 90 * they are still useful for providing reflection information, and as the 91 * component type of array classes. There is one {@code Class} instance for each 92 * primitive type, and their descriptors are: 93 * </p> 94 * <ul> 95 * <li>{@code B} representing the {@code byte} primitive type</li> 96 * <li>{@code S} representing the {@code short} primitive type</li> 97 * <li>{@code I} representing the {@code int} primitive type</li> 98 * <li>{@code J} representing the {@code long} primitive type</li> 99 * <li>{@code F} representing the {@code float} primitive type</li> 100 * <li>{@code D} representing the {@code double} primitive type</li> 101 * <li>{@code C} representing the {@code char} primitive type</li> 102 * <li>{@code Z} representing the {@code boolean} primitive type</li> 103 * <li>{@code V} representing void function return values</li> 104 * </ul> 105 * <p> 106 * <h4>Classes representing array classes</h4> 107 * <p> 108 * These represent the classes of Java arrays. There is one such {@code Class} 109 * instance per combination of array leaf component type and arity (number of 110 * dimensions). In this case, the name associated with the {@code Class} 111 * consists of one or more left square brackets (one per dimension in the array) 112 * followed by the descriptor of the class representing the leaf component type, 113 * which can be either an object type or a primitive type. The descriptor of a 114 * {@code Class} representing an array type is the same as its name. Examples 115 * of array class descriptors are: 116 * </p> 117 * <ul> 118 * <li>{@code [I} representing the {@code int[]} type</li> 119 * <li>{@code [Ljava/lang/String;} representing the {@code String[]} type</li> 120 * <li>{@code [[[C} representing the {@code char[][][]} type (three dimensions!)</li> 121 * </ul> 122 */ 123 public final class Class<T> implements Serializable, AnnotatedElement, GenericDeclaration, Type { 124 125 private static final long serialVersionUID = 3206093459760846163L; 126 127 /** defining class loader, or NULL for the "bootstrap" system loader. */ 128 private transient ClassLoader classLoader; 129 130 /** 131 * For array classes, the component class object for instanceof/checkcast (for String[][][], 132 * this will be String[][]). NULL for non-array classes. 133 */ 134 private transient Class<?> componentType; 135 /** 136 * DexCache of resolved constant pool entries. Will be null for certain VM-generated classes 137 * e.g. arrays and primitive classes. 138 */ 139 private transient DexCache dexCache; 140 141 /** Short-cut to dexCache.strings */ 142 private transient String[] dexCacheStrings; 143 144 /** static, private, and <init> methods. */ 145 private transient ArtMethod[] directMethods; 146 147 /** 148 * Instance fields. These describe the layout of the contents of an Object. Note that only the 149 * fields directly declared by this class are listed in iFields; fields declared by a 150 * superclass are listed in the superclass's Class.iFields. 151 * 152 * All instance fields that refer to objects are guaranteed to be at the beginning of the field 153 * list. {@link Class#numReferenceInstanceFields} specifies the number of reference fields. 154 */ 155 private transient ArtField[] iFields; 156 157 /** 158 * The interface table (iftable_) contains pairs of a interface class and an array of the 159 * interface methods. There is one pair per interface supported by this class. That 160 * means one pair for each interface we support directly, indirectly via superclass, or 161 * indirectly via a superinterface. This will be null if neither we nor our superclass 162 * implement any interfaces. 163 * 164 * Why we need this: given "class Foo implements Face", declare "Face faceObj = new Foo()". 165 * Invoke faceObj.blah(), where "blah" is part of the Face interface. We can't easily use a 166 * single vtable. 167 * 168 * For every interface a concrete class implements, we create an array of the concrete vtable_ 169 * methods for the methods in the interface. 170 */ 171 private transient Object[] ifTable; 172 173 /** Lazily computed name of this class; always prefer calling getName(). */ 174 private transient String name; 175 176 /** Static fields */ 177 private transient ArtField[] sFields; 178 179 /** The superclass, or NULL if this is java.lang.Object, an interface or primitive type. */ 180 private transient Class<? super T> superClass; 181 182 /** If class verify fails, we must return same error on subsequent tries. */ 183 private transient Class<?> verifyErrorClass; 184 185 /** Virtual methods defined in this class; invoked through vtable. */ 186 private transient ArtMethod[] virtualMethods; 187 188 /** 189 * Virtual method table (vtable), for use by "invoke-virtual". The vtable from the superclass 190 * is copied in, and virtual methods from our class either replace those from the super or are 191 * appended. For abstract classes, methods may be created in the vtable that aren't in 192 * virtual_ methods_ for miranda methods. 193 */ 194 private transient ArtMethod[] vtable; 195 196 /** access flags; low 16 bits are defined by VM spec */ 197 private transient int accessFlags; 198 199 /** 200 * Total size of the Class instance; used when allocating storage on GC heap. 201 * See also {@link Class#objectSize}. 202 */ 203 private transient int classSize; 204 205 /** 206 * tid used to check for recursive static initializer invocation. 207 */ 208 private transient int clinitThreadId; 209 210 /** 211 * Class def index from dex file. An index of 65535 indicates that there is no class definition, 212 * for example for an array type. 213 * TODO: really 16bits as type indices are 16bit. 214 */ 215 private transient int dexClassDefIndex; 216 217 /** 218 * Class type index from dex file, lazily computed. An index of 65535 indicates that the type 219 * index isn't known. Volatile to avoid double-checked locking bugs. 220 * TODO: really 16bits as type indices are 16bit. 221 */ 222 private transient volatile int dexTypeIndex; 223 224 /** Number of instance fields that are object references. */ 225 private transient int numReferenceInstanceFields; 226 227 /** Number of static fields that are object references. */ 228 private transient int numReferenceStaticFields; 229 230 /** 231 * Total object size; used when allocating storage on GC heap. For interfaces and abstract 232 * classes this will be zero. See also {@link Class#classSize}. 233 */ 234 private transient int objectSize; 235 236 /** Primitive type value, or 0 if not a primitive type; set for generated primitive classes. */ 237 private transient int primitiveType; 238 239 /** Bitmap of offsets of iFields. */ 240 private transient int referenceInstanceOffsets; 241 242 /** Bitmap of offsets of sFields. */ 243 private transient int referenceStaticOffsets; 244 245 /** State of class initialization */ 246 private transient int status; 247 248 private Class() { 249 // Prevent this class to be instantiated, instance should be created by JVM only 250 } 251 252 /** 253 * Returns a {@code Class} object which represents the class with 254 * the given name. The name should be the name of a non-primitive 255 * class, as described in the {@link Class class definition}. 256 * Primitive types can not be found using this method; use {@code 257 * int.class} or {@code Integer.TYPE} instead. 258 * 259 * <p>If the class has not yet been loaded, it is loaded and initialized 260 * first. This is done through either the class loader of the calling class 261 * or one of its parent class loaders. It is possible that a static initializer is run as 262 * a result of this call. 263 * 264 * @throws ClassNotFoundException 265 * if the requested class cannot be found. 266 * @throws LinkageError 267 * if an error occurs during linkage 268 * @throws ExceptionInInitializerError 269 * if an exception occurs during static initialization of a 270 * class. 271 */ 272 public static Class<?> forName(String className) throws ClassNotFoundException { 273 return forName(className, true, VMStack.getCallingClassLoader()); 274 } 275 276 /** 277 * Returns a {@code Class} object which represents the class with 278 * the given name. The name should be the name of a non-primitive 279 * class, as described in the {@link Class class definition}. 280 * Primitive types can not be found using this method; use {@code 281 * int.class} or {@code Integer.TYPE} instead. 282 * 283 * <p>If the class has not yet been loaded, it is loaded first, using the given class loader. 284 * If the class has not yet been initialized and {@code shouldInitialize} is true, 285 * the class will be initialized. 286 * 287 * @throws ClassNotFoundException 288 * if the requested class cannot be found. 289 * @throws LinkageError 290 * if an error occurs during linkage 291 * @throws ExceptionInInitializerError 292 * if an exception occurs during static initialization of a 293 * class. 294 */ 295 public static Class<?> forName(String className, boolean shouldInitialize, 296 ClassLoader classLoader) throws ClassNotFoundException { 297 298 if (classLoader == null) { 299 classLoader = ClassLoader.getSystemClassLoader(); 300 } 301 // Catch an Exception thrown by the underlying native code. It wraps 302 // up everything inside a ClassNotFoundException, even if e.g. an 303 // Error occurred during initialization. This as a workaround for 304 // an ExceptionInInitializerError that's also wrapped. It is actually 305 // expected to be thrown. Maybe the same goes for other errors. 306 // Not wrapping up all the errors will break android though. 307 Class<?> result; 308 try { 309 result = classForName(className, shouldInitialize, classLoader); 310 } catch (ClassNotFoundException e) { 311 Throwable cause = e.getCause(); 312 if (cause instanceof LinkageError) { 313 throw (LinkageError) cause; 314 } 315 throw e; 316 } 317 return result; 318 } 319 320 static native Class<?> classForName(String className, boolean shouldInitialize, 321 ClassLoader classLoader) throws ClassNotFoundException; 322 323 /** 324 * Returns an array containing {@code Class} objects for all 325 * public classes, interfaces, enums and annotations that are 326 * members of this class and its superclasses. This does not 327 * include classes of implemented interfaces. If there are no 328 * such class members or if this object represents a primitive 329 * type then an array of length 0 is returned. 330 */ 331 public Class<?>[] getClasses() { 332 List<Class<?>> result = new ArrayList<Class<?>>(); 333 for (Class<?> c = this; c != null; c = c.superClass) { 334 for (Class<?> member : c.getDeclaredClasses()) { 335 if (Modifier.isPublic(member.getModifiers())) { 336 result.add(member); 337 } 338 } 339 } 340 return result.toArray(new Class[result.size()]); 341 } 342 343 @Override public <A extends Annotation> A getAnnotation(Class<A> annotationType) { 344 return AnnotationAccess.getAnnotation(this, annotationType); 345 } 346 347 /** 348 * Returns an array containing all the annotations of this class. If there are no annotations 349 * then an empty array is returned. 350 * 351 * @see #getDeclaredAnnotations() 352 */ 353 @Override public Annotation[] getAnnotations() { 354 return AnnotationAccess.getAnnotations(this); 355 } 356 357 /** 358 * Returns the canonical name of this class. If this class does not have a 359 * canonical name as defined in the Java Language Specification, then the 360 * method returns {@code null}. 361 */ 362 public String getCanonicalName() { 363 if (isLocalClass() || isAnonymousClass()) 364 return null; 365 366 if (isArray()) { 367 /* 368 * The canonical name of an array type depends on the (existence of) 369 * the component type's canonical name. 370 */ 371 String name = getComponentType().getCanonicalName(); 372 if (name != null) { 373 return name + "[]"; 374 } 375 } else if (isMemberClass()) { 376 /* 377 * The canonical name of an inner class depends on the (existence 378 * of) the declaring class' canonical name. 379 */ 380 String name = getDeclaringClass().getCanonicalName(); 381 if (name != null) { 382 return name + "." + getSimpleName(); 383 } 384 } else { 385 /* 386 * The canonical name of a top-level class or primitive type is 387 * equal to the fully qualified name. 388 */ 389 return getName(); 390 } 391 392 /* 393 * Other classes don't have a canonical name. 394 */ 395 return null; 396 } 397 398 /** 399 * Returns the class loader which was used to load the class represented by 400 * this {@code Class}. Implementations are free to return {@code null} for 401 * classes that were loaded by the bootstrap class loader. The Android 402 * reference implementation, though, always returns a reference to an actual 403 * class loader. 404 */ 405 public ClassLoader getClassLoader() { 406 if (this.isPrimitive()) { 407 return null; 408 } 409 410 ClassLoader loader = getClassLoaderImpl(); 411 if (loader == null) { 412 loader = BootClassLoader.getInstance(); 413 } 414 return loader; 415 } 416 417 /** 418 * This must be provided by the VM vendor, as it is used by other provided 419 * class implementations in this package. Outside of this class, it is used 420 * by SecurityManager.classLoaderDepth(), 421 * currentClassLoader() and currentLoadedClass(). Return the ClassLoader for 422 * this Class without doing any security checks. The bootstrap ClassLoader 423 * is returned, unlike getClassLoader() which returns null in place of the 424 * bootstrap ClassLoader. 425 */ 426 ClassLoader getClassLoaderImpl() { 427 ClassLoader loader = classLoader; 428 return loader == null ? BootClassLoader.getInstance() : loader; 429 } 430 431 /** 432 * Returns a {@code Class} object which represents the component type if 433 * this class represents an array type. Returns {@code null} if this class 434 * does not represent an array type. The component type of an array type is 435 * the type of the elements of the array. 436 */ 437 public Class<?> getComponentType() { 438 return componentType; 439 } 440 441 /** 442 * Returns the dex file from which this class was loaded. 443 * 444 * @hide 445 */ 446 public Dex getDex() { 447 if (dexCache == null) { 448 return null; 449 } 450 return dexCache.getDex(); 451 } 452 453 /** 454 * Returns a string from the dex cache, computing the string from the dex file if necessary. 455 * 456 * @hide 457 */ 458 public String getDexCacheString(Dex dex, int dexStringIndex) { 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 */ 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 */ 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 */ 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 */ 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 */ 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 */ 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 */ 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 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 */ 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 */ 642 public Method getMethod(String name, Class<?>... parameterTypes) throws NoSuchMethodException { 643 return getMethod(name, parameterTypes, true); 644 } 645 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 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 */ 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 */ 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 getDeclaredMethodsUnchecked(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 * Populates a list of methods without performing any security or type 780 * resolution checks first. If no methods exist, the list is not modified. 781 * 782 * @param publicOnly Whether to return only public methods. 783 * @param methods A list to populate with declared methods. 784 * @hide 785 */ 786 public void getDeclaredMethodsUnchecked(boolean publicOnly, List<Method> methods) { 787 if (virtualMethods != null) { 788 for (ArtMethod m : virtualMethods) { 789 int modifiers = m.getAccessFlags(); 790 if (!publicOnly || Modifier.isPublic(modifiers)) { 791 // Add non-miranda virtual methods. 792 if ((modifiers & Modifier.MIRANDA) == 0) { 793 methods.add(new Method(m)); 794 } 795 } 796 } 797 } 798 if (directMethods != null) { 799 for (ArtMethod m : directMethods) { 800 int modifiers = m.getAccessFlags(); 801 if (!publicOnly || Modifier.isPublic(modifiers)) { 802 // Add non-constructor direct/static methods. 803 if (!Modifier.isConstructor(modifiers)) { 804 methods.add(new Method(m)); 805 } 806 } 807 } 808 } 809 } 810 811 /** 812 * Returns an array containing {@code Method} objects for all public methods 813 * for the class C represented by this {@code Class}. Methods may be 814 * declared in C, the interfaces it implements or in the superclasses of C. 815 * The elements in the returned array are in no particular order. 816 * 817 * <p>If there are no public methods or if this {@code Class} represents a 818 * primitive type or {@code void} then an empty array is returned. 819 * 820 * @see #getDeclaredMethods() 821 */ 822 public Method[] getMethods() { 823 List<Method> methods = new ArrayList<Method>(); 824 getPublicMethodsInternal(methods); 825 /* 826 * Remove duplicate methods defined by superclasses and 827 * interfaces, preferring to keep methods declared by derived 828 * types. 829 */ 830 CollectionUtils.removeDuplicates(methods, Method.ORDER_BY_SIGNATURE); 831 return methods.toArray(new Method[methods.size()]); 832 } 833 834 /** 835 * Populates {@code result} with public methods defined by this class, its 836 * superclasses, and all implemented interfaces, including overridden methods. 837 */ 838 private void getPublicMethodsInternal(List<Method> result) { 839 getDeclaredMethodsUnchecked(true, result); 840 if (!isInterface()) { 841 // Search superclasses, for interfaces don't search java.lang.Object. 842 for (Class<?> c = superClass; c != null; c = c.superClass) { 843 c.getDeclaredMethodsUnchecked(true, result); 844 } 845 } 846 // Search iftable which has a flattened and uniqued list of interfaces. 847 Object[] iftable = ifTable; 848 if (iftable != null) { 849 for (int i = 0; i < iftable.length; i += 2) { 850 Class<?> ifc = (Class<?>) iftable[i]; 851 ifc.getDeclaredMethodsUnchecked(true, result); 852 } 853 } 854 } 855 856 /** 857 * Returns the annotations that are directly defined on the class 858 * represented by this {@code Class}. Annotations that are inherited are not 859 * included in the result. If there are no annotations at all, an empty 860 * array is returned. 861 * 862 * @see #getAnnotations() 863 */ 864 @Override public Annotation[] getDeclaredAnnotations() { 865 List<Annotation> result = AnnotationAccess.getDeclaredAnnotations(this); 866 return result.toArray(new Annotation[result.size()]); 867 } 868 869 /** 870 * Returns an array containing {@code Class} objects for all classes, 871 * interfaces, enums and annotations that are members of this class. 872 */ 873 public Class<?>[] getDeclaredClasses() { 874 return AnnotationAccess.getMemberClasses(this); 875 } 876 877 /** 878 * Returns a {@code Field} object for the field with the given name 879 * which is declared in the class represented by this {@code Class}. 880 * 881 * @throws NoSuchFieldException if the requested field can not be found. 882 * @see #getField(String) 883 */ 884 public Field getDeclaredField(String name) throws NoSuchFieldException { 885 if (name == null) { 886 throw new NullPointerException("name == null"); 887 } 888 Field result = getDeclaredFieldInternal(name); 889 if (result == null) { 890 throw new NoSuchFieldException(name); 891 } else { 892 result.getType(); // Throw NoClassDefFoundError if type cannot be resolved. 893 } 894 return result; 895 } 896 897 /** 898 * Returns an array containing {@code Field} objects for all fields declared 899 * in the class represented by this {@code Class}. If there are no fields or 900 * if this {@code Class} represents an array class, a primitive type or void 901 * then an empty array is returned. 902 * 903 * @see #getFields() 904 */ 905 public Field[] getDeclaredFields() { 906 int initial_size = sFields == null ? 0 : sFields.length; 907 initial_size += iFields == null ? 0 : iFields.length; 908 ArrayList<Field> fields = new ArrayList(initial_size); 909 getDeclaredFieldsUnchecked(false, fields); 910 Field[] result = fields.toArray(new Field[fields.size()]); 911 for (Field f : result) { 912 f.getType(); // Throw NoClassDefFoundError if type cannot be resolved. 913 } 914 return result; 915 } 916 917 /** 918 * Populates a list of fields without performing any security or type 919 * resolution checks first. If no fields exist, the list is not modified. 920 * 921 * @param publicOnly Whether to return only public fields. 922 * @param fields A list to populate with declared fields. 923 * @hide 924 */ 925 public void getDeclaredFieldsUnchecked(boolean publicOnly, List<Field> fields) { 926 if (iFields != null) { 927 for (ArtField f : iFields) { 928 if (!publicOnly || Modifier.isPublic(f.getAccessFlags())) { 929 fields.add(new Field(f)); 930 } 931 } 932 } 933 if (sFields != null) { 934 for (ArtField f : sFields) { 935 if (!publicOnly || Modifier.isPublic(f.getAccessFlags())) { 936 fields.add(new Field(f)); 937 } 938 } 939 } 940 } 941 942 /** 943 * Returns the field if it is defined by this class; null otherwise. This 944 * may return a non-public member. 945 */ 946 private Field getDeclaredFieldInternal(String name) { 947 948 if (iFields != null) { 949 final ArtField matched = findByName(name, iFields); 950 if (matched != null) { 951 return new Field(matched); 952 } 953 } 954 if (sFields != null) { 955 final ArtField matched = findByName(name, sFields); 956 if (matched != null) { 957 return new Field(matched); 958 } 959 } 960 961 return null; 962 } 963 964 /** 965 * Performs a binary search through {@code fields} for a field whose name 966 * is {@code name}. Returns {@code null} if no matching field exists. 967 */ 968 private static ArtField findByName(String name, ArtField[] fields) { 969 int low = 0, high = fields.length - 1; 970 while (low <= high) { 971 final int mid = (low + high) >>> 1; 972 final ArtField f = fields[mid]; 973 final int result = f.getName().compareTo(name); 974 if (result < 0) { 975 low = mid + 1; 976 } else if (result == 0) { 977 return f; 978 } else { 979 high = mid - 1; 980 } 981 } 982 983 return null; 984 } 985 986 /** 987 * Returns the class that this class is a member of, or {@code null} if this 988 * class is a top-level class, a primitive, an array, or defined within a 989 * method or constructor. 990 */ 991 public Class<?> getDeclaringClass() { 992 if (AnnotationAccess.isAnonymousClass(this)) { 993 return null; 994 } 995 return AnnotationAccess.getEnclosingClass(this); 996 } 997 998 /** 999 * Returns the class enclosing this class. For most classes this is the same 1000 * as the {@link #getDeclaringClass() declaring class}. For classes defined 1001 * within a method or constructor (typically anonymous inner classes), this 1002 * is the declaring class of that member. 1003 */ 1004 public Class<?> getEnclosingClass() { 1005 Class<?> declaringClass = getDeclaringClass(); 1006 if (declaringClass != null) { 1007 return declaringClass; 1008 } 1009 AccessibleObject member = AnnotationAccess.getEnclosingMethodOrConstructor(this); 1010 if (member != null) { 1011 return ((Member) member).getDeclaringClass(); 1012 } 1013 return AnnotationAccess.getEnclosingClass(this); 1014 } 1015 1016 /** 1017 * Returns the enclosing {@code Constructor} of this {@code Class}, if it is an 1018 * anonymous or local/automatic class; otherwise {@code null}. 1019 */ 1020 public Constructor<?> getEnclosingConstructor() { 1021 if (classNameImpliesTopLevel()) { 1022 return null; 1023 } 1024 AccessibleObject result = AnnotationAccess.getEnclosingMethodOrConstructor(this); 1025 return result instanceof Constructor ? (Constructor<?>) result : null; 1026 } 1027 1028 /** 1029 * Returns the enclosing {@code Method} of this {@code Class}, if it is an 1030 * anonymous or local/automatic class; otherwise {@code null}. 1031 */ 1032 public Method getEnclosingMethod() { 1033 if (classNameImpliesTopLevel()) { 1034 return null; 1035 } 1036 AccessibleObject result = AnnotationAccess.getEnclosingMethodOrConstructor(this); 1037 return result instanceof Method ? (Method) result : null; 1038 } 1039 1040 /** 1041 * Returns true if this class is definitely a top level class, or false if 1042 * a more expensive check like {@link #getEnclosingClass()} is necessary. 1043 * 1044 * <p>This is a hack that exploits an implementation detail of all Java 1045 * language compilers: generated names always contain "$". As it is possible 1046 * for a top level class to be named with a "$", a false result <strong>does 1047 * not</strong> indicate that this isn't a top-level class. 1048 */ 1049 private boolean classNameImpliesTopLevel() { 1050 return !getName().contains("$"); 1051 } 1052 1053 /** 1054 * Returns the {@code enum} constants associated with this {@code Class}. 1055 * Returns {@code null} if this {@code Class} does not represent an {@code 1056 * enum} type. 1057 */ 1058 @SuppressWarnings("unchecked") // we only cast after confirming that this class is an enum 1059 public T[] getEnumConstants() { 1060 if (!isEnum()) { 1061 return null; 1062 } 1063 return (T[]) Enum.getSharedConstants((Class) this).clone(); 1064 } 1065 1066 /** 1067 * Returns a {@code Field} object which represents the public field with the 1068 * given name. This method first searches the class C represented by 1069 * this {@code Class}, then the interfaces implemented by C and finally the 1070 * superclasses of C. 1071 * 1072 * @throws NoSuchFieldException 1073 * if the field cannot be found. 1074 * @see #getDeclaredField(String) 1075 */ 1076 public Field getField(String name) throws NoSuchFieldException { 1077 if (name == null) { 1078 throw new NullPointerException("name == null"); 1079 } 1080 Field result = getPublicFieldRecursive(name); 1081 if (result == null) { 1082 throw new NoSuchFieldException(name); 1083 } else { 1084 result.getType(); // Throw NoClassDefFoundError if type cannot be resolved. 1085 } 1086 return result; 1087 } 1088 1089 private Field getPublicFieldRecursive(String name) { 1090 // search superclasses 1091 for (Class<?> c = this; c != null; c = c.superClass) { 1092 Field result = c.getDeclaredFieldInternal(name); 1093 if (result != null && (result.getModifiers() & Modifier.PUBLIC) != 0) { 1094 return result; 1095 } 1096 } 1097 1098 // search iftable which has a flattened and uniqued list of interfaces 1099 if (ifTable != null) { 1100 for (int i = 0; i < ifTable.length; i += 2) { 1101 Class<?> ifc = (Class<?>) ifTable[i]; 1102 Field result = ifc.getPublicFieldRecursive(name); 1103 if (result != null && (result.getModifiers() & Modifier.PUBLIC) != 0) { 1104 return result; 1105 } 1106 } 1107 } 1108 1109 return null; 1110 } 1111 1112 /** 1113 * Returns an array containing {@code Field} objects for all public fields 1114 * for the class C represented by this {@code Class}. Fields may be declared 1115 * in C, the interfaces it implements or in the superclasses of C. The 1116 * elements in the returned array are in no particular order. 1117 * 1118 * <p>If there are no public fields or if this class represents an array class, 1119 * a primitive type or {@code void} then an empty array is returned. 1120 * 1121 * @see #getDeclaredFields() 1122 */ 1123 public Field[] getFields() { 1124 List<Field> fields = new ArrayList<Field>(); 1125 getPublicFieldsRecursive(fields); 1126 Field[] result = fields.toArray(new Field[fields.size()]); 1127 for (Field f : result) { 1128 f.getType(); // Throw NoClassDefFoundError if type cannot be resolved. 1129 } 1130 return result; 1131 } 1132 1133 /** 1134 * Populates {@code result} with public fields defined by this class, its 1135 * superclasses, and all implemented interfaces. 1136 */ 1137 private void getPublicFieldsRecursive(List<Field> result) { 1138 // search superclasses 1139 for (Class<?> c = this; c != null; c = c.superClass) { 1140 c.getDeclaredFieldsUnchecked(true, result); 1141 } 1142 1143 // search iftable which has a flattened and uniqued list of interfaces 1144 Object[] iftable = ifTable; 1145 if (iftable != null) { 1146 for (int i = 0; i < iftable.length; i += 2) { 1147 Class<?> ifc = (Class<?>) iftable[i]; 1148 ifc.getDeclaredFieldsUnchecked(true, result); 1149 } 1150 } 1151 } 1152 1153 /** 1154 * Returns the {@link Type}s of the interfaces that this {@code Class} directly 1155 * implements. If the {@code Class} represents a primitive type or {@code 1156 * void} then an empty array is returned. 1157 */ 1158 public Type[] getGenericInterfaces() { 1159 Type[] result; 1160 synchronized (Caches.genericInterfaces) { 1161 result = Caches.genericInterfaces.get(this); 1162 if (result == null) { 1163 String annotationSignature = AnnotationAccess.getSignature(this); 1164 if (annotationSignature == null) { 1165 result = getInterfaces(); 1166 } else { 1167 GenericSignatureParser parser = new GenericSignatureParser(getClassLoader()); 1168 parser.parseForClass(this, annotationSignature); 1169 result = Types.getTypeArray(parser.interfaceTypes, false); 1170 } 1171 Caches.genericInterfaces.put(this, result); 1172 } 1173 } 1174 return (result.length == 0) ? result : result.clone(); 1175 } 1176 1177 /** 1178 * Returns the {@code Type} that represents the superclass of this {@code 1179 * class}. 1180 */ 1181 public Type getGenericSuperclass() { 1182 Type genericSuperclass = getSuperclass(); 1183 // This method is specified to return null for all cases where getSuperclass 1184 // returns null, i.e, for primitives, interfaces, void and java.lang.Object. 1185 if (genericSuperclass == null) { 1186 return null; 1187 } 1188 1189 String annotationSignature = AnnotationAccess.getSignature(this); 1190 if (annotationSignature != null) { 1191 GenericSignatureParser parser = new GenericSignatureParser(getClassLoader()); 1192 parser.parseForClass(this, annotationSignature); 1193 genericSuperclass = parser.superclassType; 1194 } 1195 return Types.getType(genericSuperclass); 1196 } 1197 1198 /** 1199 * Returns an array of {@code Class} objects that match the interfaces 1200 * in the {@code implements} declaration of the class represented 1201 * by this {@code Class}. The order of the elements in the array is 1202 * identical to the order in the original class declaration. If the class 1203 * does not implement any interfaces, an empty array is returned. 1204 * 1205 * <p>This method only returns directly-implemented interfaces, and does not 1206 * include interfaces implemented by superclasses or superinterfaces of any 1207 * implemented interfaces. 1208 */ 1209 public Class<?>[] getInterfaces() { 1210 if (isArray()) { 1211 return new Class<?>[] { Cloneable.class, Serializable.class }; 1212 } else if (isProxy()) { 1213 return getProxyInterfaces(); 1214 } 1215 Dex dex = getDex(); 1216 if (dex == null) { 1217 return EmptyArray.CLASS; 1218 } 1219 short[] interfaces = dex.interfaceTypeIndicesFromClassDefIndex(dexClassDefIndex); 1220 Class<?>[] result = new Class<?>[interfaces.length]; 1221 for (int i = 0; i < interfaces.length; i++) { 1222 result[i] = getDexCacheType(dex, interfaces[i]); 1223 } 1224 return result; 1225 } 1226 1227 // Returns the interfaces that this proxy class directly implements. 1228 private native Class<?>[] getProxyInterfaces(); 1229 1230 /** 1231 * Returns an integer that represents the modifiers of the class represented 1232 * by this {@code Class}. The returned value is a combination of bits 1233 * defined by constants in the {@link Modifier} class. 1234 */ 1235 public int getModifiers() { 1236 // Array classes inherit modifiers from their component types, but in the case of arrays 1237 // of an inner class, the class file may contain "fake" access flags because it's not valid 1238 // for a top-level class to private, say. The real access flags are stored in the InnerClass 1239 // attribute, so we need to make sure we drill down to the inner class: the accessFlags 1240 // field is not the value we want to return, and the synthesized array class does not itself 1241 // have an InnerClass attribute. https://code.google.com/p/android/issues/detail?id=56267 1242 if (isArray()) { 1243 int componentModifiers = getComponentType().getModifiers(); 1244 if ((componentModifiers & Modifier.INTERFACE) != 0) { 1245 componentModifiers &= ~(Modifier.INTERFACE | Modifier.STATIC); 1246 } 1247 return Modifier.ABSTRACT | Modifier.FINAL | componentModifiers; 1248 } 1249 int JAVA_FLAGS_MASK = 0xffff; 1250 int modifiers = AnnotationAccess.getInnerClassFlags(this, accessFlags & JAVA_FLAGS_MASK); 1251 return modifiers & JAVA_FLAGS_MASK; 1252 } 1253 1254 /** 1255 * Returns the name of the class represented by this {@code Class}. For a 1256 * description of the format which is used, see the class definition of 1257 * {@link Class}. 1258 */ 1259 public String getName() { 1260 String result = name; 1261 return (result == null) ? (name = getNameNative()) : result; 1262 } 1263 1264 private native String getNameNative(); 1265 1266 /** 1267 * Returns the simple name of the class represented by this {@code Class} as 1268 * defined in the source code. If there is no name (that is, the class is 1269 * anonymous) then an empty string is returned. If the receiver is an array 1270 * then the name of the underlying type with square braces appended (for 1271 * example {@code "Integer[]"}) is returned. 1272 * 1273 * @return the simple name of the class represented by this {@code Class}. 1274 */ 1275 public String getSimpleName() { 1276 if (isArray()) { 1277 return getComponentType().getSimpleName() + "[]"; 1278 } 1279 1280 if (isAnonymousClass()) { 1281 return ""; 1282 } 1283 1284 if (isMemberClass() || isLocalClass()) { 1285 return getInnerClassName(); 1286 } 1287 1288 String name = getName(); 1289 int dot = name.lastIndexOf('.'); 1290 if (dot != -1) { 1291 return name.substring(dot + 1); 1292 } 1293 1294 return name; 1295 } 1296 1297 /** 1298 * Returns the simple name of a member or local class, or null otherwise. 1299 */ 1300 private String getInnerClassName() { 1301 return AnnotationAccess.getInnerClassName(this); 1302 } 1303 1304 /** 1305 * Returns null. 1306 */ 1307 public ProtectionDomain getProtectionDomain() { 1308 return null; 1309 } 1310 1311 /** 1312 * Returns the URL of the given resource, or null if the resource is not found. 1313 * The mapping between the resource name and the URL is managed by the class' class loader. 1314 * 1315 * @see ClassLoader 1316 */ 1317 public URL getResource(String resourceName) { 1318 // Get absolute resource name, but without the leading slash 1319 if (resourceName.startsWith("/")) { 1320 resourceName = resourceName.substring(1); 1321 } else { 1322 String pkg = getName(); 1323 int dot = pkg.lastIndexOf('.'); 1324 if (dot != -1) { 1325 pkg = pkg.substring(0, dot).replace('.', '/'); 1326 } else { 1327 pkg = ""; 1328 } 1329 1330 resourceName = pkg + "/" + resourceName; 1331 } 1332 1333 // Delegate to proper class loader 1334 ClassLoader loader = getClassLoader(); 1335 if (loader != null) { 1336 return loader.getResource(resourceName); 1337 } else { 1338 return ClassLoader.getSystemResource(resourceName); 1339 } 1340 } 1341 1342 /** 1343 * Returns a read-only stream for the contents of the given resource, or null if the resource 1344 * is not found. 1345 * The mapping between the resource name and the stream is managed by the class' class loader. 1346 * 1347 * @see ClassLoader 1348 */ 1349 public InputStream getResourceAsStream(String resourceName) { 1350 // Get absolute resource name, but without the leading slash 1351 if (resourceName.startsWith("/")) { 1352 resourceName = resourceName.substring(1); 1353 } else { 1354 String pkg = getName(); 1355 int dot = pkg.lastIndexOf('.'); 1356 if (dot != -1) { 1357 pkg = pkg.substring(0, dot).replace('.', '/'); 1358 } else { 1359 pkg = ""; 1360 } 1361 1362 resourceName = pkg + "/" + resourceName; 1363 } 1364 1365 // Delegate to proper class loader 1366 ClassLoader loader = getClassLoader(); 1367 if (loader != null) { 1368 return loader.getResourceAsStream(resourceName); 1369 } else { 1370 return ClassLoader.getSystemResourceAsStream(resourceName); 1371 } 1372 } 1373 1374 /** 1375 * Returns null. (On Android, a {@code ClassLoader} can load classes from multiple dex files. 1376 * All classes from any given dex file will have the same signers, but different dex 1377 * files may have different signers. This does not fit well with the original 1378 * {@code ClassLoader}-based model of {@code getSigners}.) 1379 */ 1380 public Object[] getSigners() { 1381 // See http://code.google.com/p/android/issues/detail?id=1766. 1382 return null; 1383 } 1384 1385 /** 1386 * Returns the {@code Class} object which represents the superclass of the 1387 * class represented by this {@code Class}. If this {@code Class} represents 1388 * the {@code Object} class, a primitive type, an interface or void then the 1389 * method returns {@code null}. If this {@code Class} represents an array 1390 * class then the {@code Object} class is returned. 1391 */ 1392 public Class<? super T> getSuperclass() { 1393 // For interfaces superClass is Object (which agrees with the JNI spec) 1394 // but not with the expected behavior here. 1395 if (isInterface()) { 1396 return null; 1397 } else { 1398 return superClass; 1399 } 1400 } 1401 1402 /** 1403 * Returns an array containing {@code TypeVariable} objects for type 1404 * variables declared by the generic class represented by this {@code 1405 * Class}. Returns an empty array if the class is not generic. 1406 */ 1407 @SuppressWarnings("unchecked") 1408 @Override public synchronized TypeVariable<Class<T>>[] getTypeParameters() { 1409 String annotationSignature = AnnotationAccess.getSignature(this); 1410 if (annotationSignature == null) { 1411 return EmptyArray.TYPE_VARIABLE; 1412 } 1413 GenericSignatureParser parser = new GenericSignatureParser(getClassLoader()); 1414 parser.parseForClass(this, annotationSignature); 1415 return parser.formalTypeParameters; 1416 } 1417 1418 /** 1419 * Tests whether this {@code Class} represents an annotation class. 1420 */ 1421 public boolean isAnnotation() { 1422 final int ACC_ANNOTATION = 0x2000; // not public in reflect.Modifier 1423 return (accessFlags & ACC_ANNOTATION) != 0; 1424 } 1425 1426 @Override public boolean isAnnotationPresent(Class<? extends Annotation> annotationType) { 1427 return AnnotationAccess.isAnnotationPresent(this, annotationType); 1428 } 1429 1430 /** 1431 * Tests whether the class represented by this {@code Class} is 1432 * anonymous. 1433 */ 1434 public boolean isAnonymousClass() { 1435 return AnnotationAccess.isAnonymousClass(this); 1436 } 1437 1438 /** 1439 * Tests whether the class represented by this {@code Class} is an array class. 1440 */ 1441 public boolean isArray() { 1442 return getComponentType() != null; 1443 } 1444 1445 /** 1446 * Is this a runtime created proxy class? 1447 * 1448 * @hide 1449 */ 1450 public boolean isProxy() { 1451 return (accessFlags & 0x00040000) != 0; 1452 } 1453 1454 /** 1455 * Can {@code c} be assigned to this class? For example, String can be assigned to Object 1456 * (by an upcast), however, an Object cannot be assigned to a String as a potentially exception 1457 * throwing downcast would be necessary. Similarly for interfaces, a class that implements (or 1458 * an interface that extends) another can be assigned to its parent, but not vice-versa. All 1459 * Classes may assign to themselves. Classes for primitive types may not assign to each other. 1460 * 1461 * @param c the class to check. 1462 * @return {@code true} if {@code c} can be assigned to the class 1463 * represented by this {@code Class}; {@code false} otherwise. 1464 * @throws NullPointerException if {@code c} is {@code null}. 1465 */ 1466 public boolean isAssignableFrom(Class<?> c) { 1467 if (this == c) { 1468 return true; // Can always assign to things of the same type. 1469 } else if (this == Object.class) { 1470 return !c.isPrimitive(); // Can assign any reference to java.lang.Object. 1471 } else if (isArray()) { 1472 return c.isArray() && componentType.isAssignableFrom(c.componentType); 1473 } else if (isInterface()) { 1474 // Search iftable which has a flattened and uniqued list of interfaces. 1475 Object[] iftable = c.ifTable; 1476 if (iftable != null) { 1477 for (int i = 0; i < iftable.length; i += 2) { 1478 Class<?> ifc = (Class<?>) iftable[i]; 1479 if (ifc == this) { 1480 return true; 1481 } 1482 } 1483 } 1484 return false; 1485 } else { 1486 if (!c.isInterface()) { 1487 for (c = c.superClass; c != null; c = c.superClass) { 1488 if (c == this) { 1489 return true; 1490 } 1491 } 1492 } 1493 return false; 1494 } 1495 } 1496 1497 /** 1498 * Tests whether the class represented by this {@code Class} is an 1499 * {@code enum}. 1500 */ 1501 public boolean isEnum() { 1502 return (getSuperclass() == Enum.class) && ((accessFlags & 0x4000) != 0); 1503 } 1504 1505 /** 1506 * Tests whether the given object can be cast to the class 1507 * represented by this {@code Class}. This is the runtime version of the 1508 * {@code instanceof} operator. 1509 * 1510 * @return {@code true} if {@code object} can be cast to the type 1511 * represented by this {@code Class}; {@code false} if {@code 1512 * object} is {@code null} or cannot be cast. 1513 */ 1514 public boolean isInstance(Object object) { 1515 if (object == null) { 1516 return false; 1517 } 1518 return isAssignableFrom(object.getClass()); 1519 } 1520 1521 /** 1522 * Tests whether this {@code Class} represents an interface. 1523 */ 1524 public boolean isInterface() { 1525 return (accessFlags & Modifier.INTERFACE) != 0; 1526 } 1527 1528 /** 1529 * Tests whether the class represented by this {@code Class} is defined 1530 * locally. 1531 */ 1532 public boolean isLocalClass() { 1533 return !classNameImpliesTopLevel() 1534 && AnnotationAccess.getEnclosingMethodOrConstructor(this) != null 1535 && !isAnonymousClass(); 1536 } 1537 1538 /** 1539 * Tests whether the class represented by this {@code Class} is a member 1540 * class. 1541 */ 1542 public boolean isMemberClass() { 1543 return getDeclaringClass() != null; 1544 } 1545 1546 /** 1547 * Tests whether this {@code Class} represents a primitive type. 1548 */ 1549 public boolean isPrimitive() { 1550 return primitiveType != 0; 1551 } 1552 1553 /** 1554 * Tests whether this {@code Class} represents a synthetic type. 1555 */ 1556 public boolean isSynthetic() { 1557 final int ACC_SYNTHETIC = 0x1000; // not public in reflect.Modifier 1558 return (accessFlags & ACC_SYNTHETIC) != 0; 1559 } 1560 1561 /** 1562 * Indicates whether this {@code Class} or its parents override finalize. 1563 * 1564 * @hide 1565 */ 1566 public boolean isFinalizable() { 1567 final int ACC_CLASS_IS_FINALIZABLE = 0x80000000; // not public in reflect.Modifier 1568 return (accessFlags & ACC_CLASS_IS_FINALIZABLE) != 0; 1569 } 1570 1571 /** 1572 * Returns a new instance of the class represented by this {@code Class}, 1573 * created by invoking the default (that is, zero-argument) constructor. If 1574 * there is no such constructor, or if the creation fails (either because of 1575 * a lack of available memory or because an exception is thrown by the 1576 * constructor), an {@code InstantiationException} is thrown. If the default 1577 * constructor exists but is not accessible from the context where this 1578 * method is invoked, an {@code IllegalAccessException} is thrown. 1579 * 1580 * @throws IllegalAccessException 1581 * if the default constructor is not visible. 1582 * @throws InstantiationException 1583 * if the instance cannot be created. 1584 */ 1585 public T newInstance() throws InstantiationException, IllegalAccessException { 1586 if (isPrimitive() || isInterface() || isArray() || Modifier.isAbstract(accessFlags)) { 1587 throw new InstantiationException(this + " cannot be instantiated"); 1588 } 1589 Class<?> caller = VMStack.getStackClass1(); 1590 if (!caller.canAccess(this)) { 1591 throw new IllegalAccessException(this + " is not accessible from " + caller); 1592 } 1593 Constructor<T> init; 1594 try { 1595 init = getDeclaredConstructor(); 1596 } catch (NoSuchMethodException e) { 1597 InstantiationException t = 1598 new InstantiationException(this + " has no zero argument constructor"); 1599 t.initCause(e); 1600 throw t; 1601 } 1602 if (!caller.canAccessMember(this, init.getAccessFlags())) { 1603 throw new IllegalAccessException(init + " is not accessible from " + caller); 1604 } 1605 try { 1606 return init.newInstance(null, init.isAccessible()); 1607 } catch (InvocationTargetException e) { 1608 SneakyThrow.sneakyThrow(e.getCause()); 1609 return null; // Unreachable. 1610 } 1611 } 1612 1613 private boolean canAccess(Class<?> c) { 1614 if(Modifier.isPublic(c.accessFlags)) { 1615 return true; 1616 } 1617 return inSamePackage(c); 1618 } 1619 1620 private boolean canAccessMember(Class<?> memberClass, int memberModifiers) { 1621 if (memberClass == this || Modifier.isPublic(memberModifiers)) { 1622 return true; 1623 } 1624 if (Modifier.isPrivate(memberModifiers)) { 1625 return false; 1626 } 1627 if (Modifier.isProtected(memberModifiers)) { 1628 for (Class<?> parent = this.superClass; parent != null; parent = parent.superClass) { 1629 if (parent == memberClass) { 1630 return true; 1631 } 1632 } 1633 } 1634 return inSamePackage(memberClass); 1635 } 1636 1637 private boolean inSamePackage(Class<?> c) { 1638 if (classLoader != c.classLoader) { 1639 return false; 1640 } 1641 String packageName1 = getPackageName$(); 1642 String packageName2 = c.getPackageName$(); 1643 if (packageName1 == null) { 1644 return packageName2 == null; 1645 } else if (packageName2 == null) { 1646 return false; 1647 } else { 1648 return packageName1.equals(packageName2); 1649 } 1650 } 1651 1652 @Override 1653 public String toString() { 1654 if (isPrimitive()) { 1655 return getSimpleName(); 1656 } else { 1657 return (isInterface() ? "interface " : "class ") + getName(); 1658 } 1659 } 1660 1661 /** 1662 * Returns the {@code Package} of which the class represented by this 1663 * {@code Class} is a member. Returns {@code null} if no {@code Package} 1664 * object was created by the class loader of the class. 1665 */ 1666 public Package getPackage() { 1667 // TODO This might be a hack, but the VM doesn't have the necessary info. 1668 ClassLoader loader = getClassLoader(); 1669 if (loader != null) { 1670 String packageName = getPackageName$(); 1671 return packageName != null ? loader.getPackage(packageName) : null; 1672 } 1673 return null; 1674 } 1675 1676 /** 1677 * Returns the package name of this class. This returns null for classes in 1678 * the default package. 1679 * 1680 * @hide 1681 */ 1682 public String getPackageName$() { 1683 String name = getName(); 1684 int last = name.lastIndexOf('.'); 1685 return last == -1 ? null : name.substring(0, last); 1686 } 1687 1688 /** 1689 * Returns the assertion status for the class represented by this {@code 1690 * Class}. Assertion is enabled / disabled based on the class loader, 1691 * package or class default at runtime. 1692 */ 1693 public boolean desiredAssertionStatus() { 1694 return false; 1695 } 1696 1697 /** 1698 * Casts this {@code Class} to represent a subclass of the given class. 1699 * If successful, this {@code Class} is returned; otherwise a {@code 1700 * ClassCastException} is thrown. 1701 * 1702 * @throws ClassCastException 1703 * if this {@code Class} cannot be cast to the given type. 1704 */ 1705 @SuppressWarnings("unchecked") 1706 public <U> Class<? extends U> asSubclass(Class<U> c) { 1707 if (c.isAssignableFrom(this)) { 1708 return (Class<? extends U>)this; 1709 } 1710 String actualClassName = this.getName(); 1711 String desiredClassName = c.getName(); 1712 throw new ClassCastException(actualClassName + " cannot be cast to " + desiredClassName); 1713 } 1714 1715 /** 1716 * Casts the given object to the type represented by this {@code Class}. 1717 * If the object is {@code null} then the result is also {@code null}. 1718 * 1719 * @throws ClassCastException 1720 * if the object cannot be cast to the given type. 1721 */ 1722 @SuppressWarnings("unchecked") 1723 public T cast(Object obj) { 1724 if (obj == null) { 1725 return null; 1726 } else if (this.isInstance(obj)) { 1727 return (T)obj; 1728 } 1729 String actualClassName = obj.getClass().getName(); 1730 String desiredClassName = this.getName(); 1731 throw new ClassCastException(actualClassName + " cannot be cast to " + desiredClassName); 1732 } 1733 1734 /** 1735 * The class def of this class in its own Dex, or -1 if there is no class def. 1736 * 1737 * @hide 1738 */ 1739 public int getDexClassDefIndex() { 1740 return (dexClassDefIndex == 65535) ? -1 : dexClassDefIndex; 1741 } 1742 1743 /** 1744 * The type index of this class in its own Dex, or -1 if it is unknown. If a class is referenced 1745 * by multiple Dex files, it will have a different type index in each. Dex files support 65534 1746 * type indices, with 65535 representing no index. 1747 * 1748 * @hide 1749 */ 1750 public int getDexTypeIndex() { 1751 int typeIndex = dexTypeIndex; 1752 if (typeIndex != 65535) { 1753 return typeIndex; 1754 } 1755 synchronized (this) { 1756 typeIndex = dexTypeIndex; 1757 if (typeIndex == 65535) { 1758 if (dexClassDefIndex >= 0) { 1759 typeIndex = getDex().typeIndexFromClassDefIndex(dexClassDefIndex); 1760 } else { 1761 typeIndex = getDex().findTypeIndex(InternalNames.getInternalName(this)); 1762 if (typeIndex < 0) { 1763 typeIndex = -1; 1764 } 1765 } 1766 dexTypeIndex = typeIndex; 1767 } 1768 } 1769 return typeIndex; 1770 } 1771 1772 /** 1773 * The annotation directory offset of this class in its own Dex, or 0 if it 1774 * is unknown. 1775 * 1776 * TODO: 0 is a sentinel that means 'no annotations directory'; this should be -1 if unknown 1777 * 1778 * @hide 1779 */ 1780 public int getDexAnnotationDirectoryOffset() { 1781 Dex dex = getDex(); 1782 if (dex == null) { 1783 return 0; 1784 } 1785 int classDefIndex = getDexClassDefIndex(); 1786 if (classDefIndex < 0) { 1787 return 0; 1788 } 1789 return dex.annotationDirectoryOffsetFromClassDefIndex(classDefIndex); 1790 } 1791 1792 private static class Caches { 1793 /** 1794 * Cache to avoid frequent recalculation of generic interfaces, which is generally uncommon. 1795 * Sized sufficient to allow ConcurrentHashMapTest to run without recalculating its generic 1796 * interfaces (required to avoid time outs). Validated by running reflection heavy code 1797 * such as applications using Guice-like frameworks. 1798 */ 1799 private static final BasicLruCache<Class, Type[]> genericInterfaces 1800 = new BasicLruCache<Class, Type[]>(8); 1801 } 1802 } 1803