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 33package java.lang; 34 35import com.android.dex.Dex; 36import dalvik.system.VMStack; 37import java.io.InputStream; 38import java.io.Serializable; 39import java.lang.annotation.Annotation; 40import java.lang.annotation.Inherited; 41import java.lang.reflect.AnnotatedElement; 42import java.lang.reflect.Constructor; 43import java.lang.reflect.Field; 44import java.lang.reflect.GenericDeclaration; 45import java.lang.reflect.Member; 46import java.lang.reflect.Method; 47import java.lang.reflect.Modifier; 48import java.lang.reflect.Type; 49import java.lang.reflect.TypeVariable; 50import java.net.URL; 51import java.security.ProtectionDomain; 52import java.util.ArrayList; 53import java.util.Arrays; 54import java.util.Collection; 55import java.util.HashMap; 56import java.util.List; 57import org.apache.harmony.kernel.vm.StringUtils; 58import libcore.reflect.AnnotationAccess; 59import libcore.reflect.GenericSignatureParser; 60import libcore.reflect.InternalNames; 61import libcore.reflect.Types; 62import libcore.util.BasicLruCache; 63import libcore.util.CollectionUtils; 64import libcore.util.EmptyArray; 65 66/** 67 * The in-memory representation of a Java class. This representation serves as 68 * the starting point for querying class-related information, a process usually 69 * called "reflection". There are basically three types of {@code Class} 70 * instances: those representing real classes and interfaces, those representing 71 * primitive types, and those representing array classes. 72 * 73 * <h4>Class instances representing object types (classes or interfaces)</h4> 74 * <p> 75 * These represent an ordinary class or interface as found in the class 76 * hierarchy. The name associated with these {@code Class} instances is simply 77 * the fully qualified class name of the class or interface that it represents. 78 * In addition to this human-readable name, each class is also associated by a 79 * so-called <em>signature</em>, which is the letter "L", followed by the 80 * class name and a semicolon (";"). The signature is what the runtime system 81 * uses internally for identifying the class (for example in a DEX file). 82 * </p> 83 * <h4>Classes representing primitive types</h4> 84 * <p> 85 * These represent the standard Java primitive types and hence share their 86 * names (for example "int" for the {@code int} primitive type). Although it is 87 * not possible to create new instances based on these {@code Class} instances, 88 * they are still useful for providing reflection information, and as the 89 * component type of array classes. There is one {@code Class} instance for each 90 * primitive type, and their signatures are: 91 * </p> 92 * <ul> 93 * <li>{@code B} representing the {@code byte} primitive type</li> 94 * <li>{@code S} representing the {@code short} primitive type</li> 95 * <li>{@code I} representing the {@code int} primitive type</li> 96 * <li>{@code J} representing the {@code long} primitive type</li> 97 * <li>{@code F} representing the {@code float} primitive type</li> 98 * <li>{@code D} representing the {@code double} primitive type</li> 99 * <li>{@code C} representing the {@code char} primitive type</li> 100 * <li>{@code Z} representing the {@code boolean} primitive type</li> 101 * <li>{@code V} representing void function return values</li> 102 * </ul> 103 * <p> 104 * <h4>Classes representing array classes</h4> 105 * <p> 106 * These represent the classes of Java arrays. There is one such {@code Class} 107 * instance per combination of array leaf component type and arity (number of 108 * dimensions). In this case, the name associated with the {@code Class} 109 * consists of one or more left square brackets (one per dimension in the array) 110 * followed by the signature of the class representing the leaf component type, 111 * which can be either an object type or a primitive type. The signature of a 112 * {@code Class} representing an array type is the same as its name. Examples 113 * of array class signatures are: 114 * </p> 115 * <ul> 116 * <li>{@code [I} representing the {@code int[]} type</li> 117 * <li>{@code [Ljava/lang/String;} representing the {@code String[]} type</li> 118 * <li>{@code [[[C} representing the {@code char[][][]} type (three dimensions!)</li> 119 * </ul> 120 */ 121public final class Class<T> implements Serializable, AnnotatedElement, GenericDeclaration, Type { 122 123 private static final long serialVersionUID = 3206093459760846163L; 124 125 /** 126 * Class def index from dex file. An index of -1 indicates that there is no class definition, 127 * for example for an array type. 128 */ 129 private transient int dexClassDefIndex; 130 131 /** The type index of this class within the dex file that defines it. */ 132 private transient int dexTypeIndex; 133 134 /** 135 * Have we computed the type and class def indices? Volatile to avoid double check locking bugs. 136 */ 137 private transient volatile boolean dexIndicesInitialized; 138 139 /** 140 * Lazily computed name of this class; always prefer calling getName(). 141 */ 142 private transient String name; 143 144 private Class() { 145 // Prevent this class to be instantiated, instance 146 // should be created by JVM only 147 } 148 149 /** 150 * Returns the dex file from which this class was loaded. 151 * @hide 152 */ 153 public native Dex getDex(); 154 155 /** Lazily compute indices in to Dex */ 156 private synchronized void computeDexIndices() { 157 if (!dexIndicesInitialized) { 158 Dex dex = getDex(); 159 dexTypeIndex = dex.findTypeIndex(InternalNames.getInternalName(this)); 160 if (dexTypeIndex < 0) { 161 dexTypeIndex = -1; 162 dexClassDefIndex = -1; 163 } else { 164 dexClassDefIndex = dex.findClassDefIndexFromTypeIndex(dexTypeIndex); 165 } 166 dexIndicesInitialized = true; 167 } 168 } 169 170 /** 171 * The class def of this class in its own Dex, or -1 if there is no class def. 172 * 173 * @hide 174 */ 175 public int getDexClassDefIndex() { 176 if (!dexIndicesInitialized) { 177 computeDexIndices(); 178 } 179 return dexClassDefIndex; 180 } 181 182 /** 183 * The type index of this class in its own Dex, or -1 if it is unknown. If a class is referenced 184 * by multiple Dex files, it will have a different type index in each. Dex files support 65534 185 * type indices, with 65535 representing no index. 186 * 187 * @hide 188 */ 189 public int getDexTypeIndex() { 190 if (!dexIndicesInitialized) { 191 computeDexIndices(); 192 } 193 return dexTypeIndex; 194 } 195 196 /** 197 * Returns a {@code Class} object which represents the class with the 198 * given name. The name should be the name of a non-primitive class, as described in 199 * the {@link Class class definition}. 200 * Primitive types can not be found using this method; use {@code int.class} or {@code Integer.TYPE} instead. 201 * 202 * <p>If the class has not yet been loaded, it is loaded and initialized 203 * first. This is done through either the class loader of the calling class 204 * or one of its parent class loaders. It is possible that a static initializer is run as 205 * a result of this call. 206 * 207 * @throws ClassNotFoundException 208 * if the requested class can not be found. 209 * @throws LinkageError 210 * if an error occurs during linkage 211 * @throws ExceptionInInitializerError 212 * if an exception occurs during static initialization of a 213 * class. 214 */ 215 public static Class<?> forName(String className) throws ClassNotFoundException { 216 return forName(className, true, VMStack.getCallingClassLoader()); 217 } 218 219 /** 220 * Returns a {@code Class} object which represents the class with the 221 * given name. The name should be the name of a non-primitive class, as described in 222 * the {@link Class class definition}. 223 * Primitive types can not be found using this method; use {@code int.class} or {@code Integer.TYPE} instead. 224 * 225 * <p>If the class has not yet been loaded, it is loaded first, using the given class loader. 226 * If the class has not yet been initialized and {@code shouldInitialize} is true, 227 * the class will be initialized. 228 * 229 * @throws ClassNotFoundException 230 * if the requested class can not be found. 231 * @throws LinkageError 232 * if an error occurs during linkage 233 * @throws ExceptionInInitializerError 234 * if an exception occurs during static initialization of a 235 * class. 236 */ 237 public static Class<?> forName(String className, boolean shouldInitialize, 238 ClassLoader classLoader) throws ClassNotFoundException { 239 240 if (classLoader == null) { 241 classLoader = ClassLoader.getSystemClassLoader(); 242 } 243 // Catch an Exception thrown by the underlying native code. It wraps 244 // up everything inside a ClassNotFoundException, even if e.g. an 245 // Error occurred during initialization. This as a workaround for 246 // an ExceptionInInitializerError that's also wrapped. It is actually 247 // expected to be thrown. Maybe the same goes for other errors. 248 // Not wrapping up all the errors will break android though. 249 Class<?> result; 250 try { 251 result = classForName(className, shouldInitialize, 252 classLoader); 253 } catch (ClassNotFoundException e) { 254 Throwable cause = e.getCause(); 255 if (cause instanceof ExceptionInInitializerError) { 256 throw (ExceptionInInitializerError) cause; 257 } 258 throw e; 259 } 260 return result; 261 } 262 263 private static native Class<?> classForName(String className, boolean shouldInitialize, 264 ClassLoader classLoader) throws ClassNotFoundException; 265 266 /** 267 * Returns an array containing {@code Class} objects for all public classes 268 * and interfaces that are members of this class. This includes public 269 * members inherited from super classes and interfaces. If there are no such 270 * class members or if this object represents a primitive type then an array 271 * of length 0 is returned. 272 */ 273 public Class<?>[] getClasses() { 274 Class<?>[] result = getDeclaredClasses(this, true); 275 // Traverse all superclasses. 276 for (Class<?> c = this.getSuperclass(); c != null; c = c.getSuperclass()) { 277 Class<?>[] temp = getDeclaredClasses(c, true); 278 if (temp.length != 0) { 279 result = arraycopy(new Class[result.length + temp.length], result, temp); 280 } 281 } 282 return result; 283 } 284 285 @Override public <A extends Annotation> A getAnnotation(Class<A> annotationType) { 286 if (annotationType == null) { 287 throw new NullPointerException("annotationType == null"); 288 } 289 290 A annotation = getDeclaredAnnotation(annotationType); 291 if (annotation != null) { 292 return annotation; 293 } 294 295 if (annotationType.isAnnotationPresent(Inherited.class)) { 296 for (Class<?> sup = getSuperclass(); sup != null; sup = sup.getSuperclass()) { 297 annotation = sup.getDeclaredAnnotation(annotationType); 298 if (annotation != null) { 299 return annotation; 300 } 301 } 302 } 303 304 return null; 305 } 306 307 /** 308 * Returns an array containing all the annotations of this class. If there are no annotations 309 * then an empty array is returned. 310 * 311 * @see #getDeclaredAnnotations() 312 */ 313 public Annotation[] getAnnotations() { 314 /* 315 * We need to get the annotations declared on this class, plus the 316 * annotations from superclasses that have the "@Inherited" annotation 317 * set. We create a temporary map to use while we accumulate the 318 * annotations and convert it to an array at the end. 319 * 320 * It's possible to have duplicates when annotations are inherited. 321 * We use a Map to filter those out. 322 * 323 * HashMap might be overkill here. 324 */ 325 HashMap<Class, Annotation> map = new HashMap<Class, Annotation>(); 326 Annotation[] declaredAnnotations = getDeclaredAnnotations(); 327 328 for (int i = declaredAnnotations.length-1; i >= 0; --i) { 329 map.put(declaredAnnotations[i].annotationType(), declaredAnnotations[i]); 330 } 331 for (Class<?> sup = getSuperclass(); sup != null; sup = sup.getSuperclass()) { 332 declaredAnnotations = sup.getDeclaredAnnotations(); 333 for (int i = declaredAnnotations.length-1; i >= 0; --i) { 334 Class<?> clazz = declaredAnnotations[i].annotationType(); 335 if (!map.containsKey(clazz) && clazz.isAnnotationPresent(Inherited.class)) { 336 map.put(clazz, declaredAnnotations[i]); 337 } 338 } 339 } 340 341 /* convert annotation values from HashMap to array */ 342 Collection<Annotation> coll = map.values(); 343 return coll.toArray(new Annotation[coll.size()]); 344 } 345 346 /** 347 * Returns the canonical name of this class. If this class does not have a 348 * canonical name as defined in the Java Language Specification, then the 349 * method returns {@code null}. 350 */ 351 public String getCanonicalName() { 352 if (isLocalClass() || isAnonymousClass()) 353 return null; 354 355 if (isArray()) { 356 /* 357 * The canonical name of an array type depends on the (existence of) 358 * the component type's canonical name. 359 */ 360 String name = getComponentType().getCanonicalName(); 361 if (name != null) { 362 return name + "[]"; 363 } 364 } else if (isMemberClass()) { 365 /* 366 * The canonical name of an inner class depends on the (existence 367 * of) the declaring class' canonical name. 368 */ 369 String name = getDeclaringClass().getCanonicalName(); 370 if (name != null) { 371 return name + "." + getSimpleName(); 372 } 373 } else { 374 /* 375 * The canonical name of a top-level class or primitive type is 376 * equal to the fully qualified name. 377 */ 378 return getName(); 379 } 380 381 /* 382 * Other classes don't have a canonical name. 383 */ 384 return null; 385 } 386 387 /** 388 * Returns the class loader which was used to load the class represented by 389 * this {@code Class}. Implementations are free to return {@code null} for 390 * classes that were loaded by the bootstrap class loader. The Android 391 * reference implementation, though, always returns a reference to an actual 392 * class loader. 393 */ 394 public ClassLoader getClassLoader() { 395 if (this.isPrimitive()) { 396 return null; 397 } 398 399 ClassLoader loader = getClassLoaderImpl(); 400 if (loader == null) { 401 loader = BootClassLoader.getInstance(); 402 } 403 return loader; 404 } 405 406 /** 407 * This must be provided by the VM vendor, as it is used by other provided 408 * class implementations in this package. Outside of this class, it is used 409 * by SecurityManager.classLoaderDepth(), 410 * currentClassLoader() and currentLoadedClass(). Return the ClassLoader for 411 * this Class without doing any security checks. The bootstrap ClassLoader 412 * is returned, unlike getClassLoader() which returns null in place of the 413 * bootstrap ClassLoader. 414 */ 415 ClassLoader getClassLoaderImpl() { 416 ClassLoader loader = getClassLoader(this); 417 return loader == null ? BootClassLoader.getInstance() : loader; 418 } 419 420 /* 421 * Returns the defining class loader for the given class. 422 */ 423 private static native ClassLoader getClassLoader(Class<?> c); 424 425 /** 426 * Returns a {@code Class} object which represents the component type if 427 * this class represents an array type. Returns {@code null} if this class 428 * does not represent an array type. The component type of an array type is 429 * the type of the elements of the array. 430 */ 431 public native Class<?> getComponentType(); 432 433 /** 434 * Returns a {@code Constructor} object which represents the public 435 * constructor matching the given parameter types. 436 * {@code (Class[]) null} is equivalent to the empty array. 437 * 438 * <p>See {@link #getMethod} for details of the search order. 439 * Use {@link #getDeclaredConstructor} if you don't want to search superclasses. 440 * 441 * @throws NoSuchMethodException 442 * if the constructor can not be found. 443 */ 444 @SuppressWarnings("unchecked") 445 public Constructor<T> getConstructor(Class<?>... parameterTypes) throws NoSuchMethodException { 446 return (Constructor) getConstructorOrMethod("<init>", false, true, parameterTypes); 447 } 448 449 /** 450 * Returns a constructor or method with the given name. Use "<init>" to return a constructor. 451 */ 452 private Member getConstructorOrMethod(String name, boolean searchSuperTypes, 453 boolean publicOnly, Class<?>[] parameterTypes) throws NoSuchMethodException { 454 if (searchSuperTypes && !publicOnly) { 455 throw new AssertionError(); // can't lookup non-public members recursively 456 } 457 if (name == null) { 458 throw new NullPointerException("name == null"); 459 } 460 if (parameterTypes == null) { 461 parameterTypes = EmptyArray.CLASS; 462 } 463 for (Class<?> c : parameterTypes) { 464 if (c == null) { 465 throw new NoSuchMethodException("parameter type is null"); 466 } 467 } 468 Member result = searchSuperTypes 469 ? getPublicConstructorOrMethodRecursive(name, parameterTypes) 470 : Class.getDeclaredConstructorOrMethod(this, name, parameterTypes); 471 if (result == null || publicOnly && (result.getModifiers() & Modifier.PUBLIC) == 0) { 472 throw new NoSuchMethodException(name + " " + Arrays.toString(parameterTypes)); 473 } 474 return result; 475 } 476 477 private Member getPublicConstructorOrMethodRecursive(String name, Class<?>[] parameterTypes) { 478 // search superclasses 479 for (Class<?> c = this; c != null; c = c.getSuperclass()) { 480 Member result = Class.getDeclaredConstructorOrMethod(c, name, parameterTypes); 481 if (result != null && (result.getModifiers() & Modifier.PUBLIC) != 0) { 482 return result; 483 } 484 } 485 486 // search implemented interfaces 487 for (Class<?> c = this; c != null; c = c.getSuperclass()) { 488 for (Class<?> ifc : c.getInterfaces()) { 489 Member result = ifc.getPublicConstructorOrMethodRecursive(name, parameterTypes); 490 if (result != null && (result.getModifiers() & Modifier.PUBLIC) != 0) { 491 return result; 492 } 493 } 494 } 495 496 return null; 497 } 498 499 /** 500 * Returns an array containing {@code Constructor} objects for all public 501 * constructors for this {@code Class}. If there 502 * are no public constructors or if this {@code Class} represents an array 503 * class, a primitive type or void then an empty array is returned. 504 * 505 * @see #getDeclaredConstructors() 506 */ 507 public Constructor<?>[] getConstructors() { 508 return getDeclaredConstructors(this, true); 509 } 510 511 /** 512 * Returns the annotations that are directly defined on the class 513 * represented by this {@code Class}. Annotations that are inherited are not 514 * included in the result. If there are no annotations at all, an empty 515 * array is returned. 516 * 517 * @see #getAnnotations() 518 */ 519 public native Annotation[] getDeclaredAnnotations(); 520 521 /** 522 * Returns the annotation if it exists. 523 */ 524 native private <A extends Annotation> A getDeclaredAnnotation(Class<A> annotationClass); 525 526 /** 527 * Returns true if the annotation exists. 528 */ 529 native private boolean isDeclaredAnnotationPresent(Class<? extends Annotation> annotationClass); 530 531 /** 532 * Returns an array containing {@code Class} objects for all classes and 533 * interfaces that are declared as members of the class which this {@code 534 * Class} represents. If there are no classes or interfaces declared or if 535 * this class represents an array class, a primitive type or void, then an 536 * empty array is returned. 537 */ 538 public Class<?>[] getDeclaredClasses() { 539 return getDeclaredClasses(this, false); 540 } 541 542 /* 543 * Returns the list of member classes of the given class. 544 * If no members exist, an empty array is returned. 545 */ 546 private static native Class<?>[] getDeclaredClasses(Class<?> c, boolean publicOnly); 547 548 /** 549 * Returns a {@code Constructor} object which represents the constructor 550 * matching the given parameter types that is declared by the class 551 * represented by this {@code Class}. 552 * {@code (Class[]) null} is equivalent to the empty array. 553 * 554 * <p>Use {@link #getConstructor} if you want to search superclasses. 555 * 556 * @throws NoSuchMethodException 557 * if the requested constructor can not be found. 558 */ 559 @SuppressWarnings("unchecked") 560 public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes) 561 throws NoSuchMethodException { 562 return (Constructor) getConstructorOrMethod("<init>", false, false, parameterTypes); 563 } 564 565 /** 566 * Returns an array containing {@code Constructor} objects for all 567 * constructors declared in the class represented by this {@code Class}. If 568 * there are no constructors or if this {@code Class} represents an array 569 * class, a primitive type, or void then an empty array is returned. 570 * 571 * @see #getConstructors() 572 */ 573 public Constructor<?>[] getDeclaredConstructors() { 574 return getDeclaredConstructors(this, false); 575 } 576 577 /* 578 * Returns the list of constructors. If no constructors exist, an empty array is returned. 579 */ 580 private static native <T> Constructor<T>[] getDeclaredConstructors(Class<T> c, 581 boolean publicOnly); 582 583 /** 584 * Returns a {@code Field} object for the field with the given name 585 * which is declared in the class represented by this {@code Class}. 586 * 587 * @throws NoSuchFieldException if the requested field can not be found. 588 * @see #getField(String) 589 */ 590 public Field getDeclaredField(String name) throws NoSuchFieldException { 591 if (name == null) { 592 throw new NullPointerException("name == null"); 593 } 594 Field result = getDeclaredField(this, name); 595 if (result == null) { 596 throw new NoSuchFieldException(name); 597 } 598 return result; 599 } 600 601 /** 602 * Returns an array containing {@code Field} objects for all fields declared 603 * in the class represented by this {@code Class}. If there are no fields or 604 * if this {@code Class} represents an array class, a primitive type or void 605 * then an empty array is returned. 606 * 607 * @see #getFields() 608 */ 609 public Field[] getDeclaredFields() { 610 return getDeclaredFields(this, false); 611 } 612 613 /* 614 * Returns the list of fields without performing any security checks 615 * first. If no fields exist at all, an empty array is returned. 616 */ 617 static native Field[] getDeclaredFields(Class<?> c, boolean publicOnly); 618 619 /** 620 * Returns the field if it is defined by {@code c}; null otherwise. This 621 * may return a non-public member. 622 */ 623 static native Field getDeclaredField(Class<?> c, String name); 624 625 /** 626 * Returns a {@code Method} object which represents the method matching the 627 * given name and parameter types that is declared by the class 628 * represented by this {@code Class}. 629 * {@code (Class[]) null} is equivalent to the empty array. 630 * 631 * <p>See {@link #getMethod} if you want to search superclasses. 632 * 633 * @throws NoSuchMethodException 634 * if the requested method can not be found. 635 * @throws NullPointerException 636 * if {@code name} is {@code null}. 637 */ 638 public Method getDeclaredMethod(String name, Class<?>... parameterTypes) 639 throws NoSuchMethodException { 640 Member member = getConstructorOrMethod(name, false, false, parameterTypes); 641 if (member instanceof Constructor) { 642 throw new NoSuchMethodException(name); 643 } 644 return (Method) member; 645 } 646 647 /** 648 * Returns an array containing {@code Method} objects for all methods 649 * declared in the class represented by this {@code Class}. If there are no 650 * methods or if this {@code Class} represents an array class, a primitive 651 * type or void then an empty array is returned. 652 * 653 * @see #getMethods() 654 */ 655 public Method[] getDeclaredMethods() { 656 return getDeclaredMethods(this, false); 657 } 658 659 /** 660 * Returns the list of methods. If no methods exist, an empty array is returned. 661 */ 662 static native Method[] getDeclaredMethods(Class<?> c, boolean publicOnly); 663 664 /** 665 * Returns the constructor or method if it is defined by {@code c}; null 666 * otherwise. This may return a non-public member. Use "<init>" to get a constructor. 667 */ 668 static native Member getDeclaredConstructorOrMethod(Class c, String name, Class[] args); 669 670 /** 671 * Returns the declaring {@code Class} of this {@code Class}. Returns 672 * {@code null} if the class is not a member of another class or if this 673 * {@code Class} represents an array class, a primitive type, or void. 674 */ 675 public native Class<?> getDeclaringClass(); 676 677 /** 678 * Returns the enclosing {@code Class} of this {@code Class}. If there is no 679 * enclosing class the method returns {@code null}. 680 */ 681 public native Class<?> getEnclosingClass(); 682 683 /** 684 * Returns the enclosing {@code Constructor} of this {@code Class}, if it is an 685 * anonymous or local/automatic class; otherwise {@code null}. 686 */ 687 public native Constructor<?> getEnclosingConstructor(); 688 689 /** 690 * Returns the enclosing {@code Method} of this {@code Class}, if it is an 691 * anonymous or local/automatic class; otherwise {@code null}. 692 */ 693 public native Method getEnclosingMethod(); 694 695 /** 696 * Returns the {@code enum} constants associated with this {@code Class}. 697 * Returns {@code null} if this {@code Class} does not represent an {@code 698 * enum} type. 699 */ 700 @SuppressWarnings("unchecked") // we only cast after confirming that this class is an enum 701 public T[] getEnumConstants() { 702 if (!isEnum()) { 703 return null; 704 } 705 return (T[]) Enum.getSharedConstants((Class) this).clone(); 706 } 707 708 /** 709 * Returns a {@code Field} object which represents the public field with the 710 * given name. This method first searches the class C represented by 711 * this {@code Class}, then the interfaces implemented by C and finally the 712 * superclasses of C. 713 * 714 * @throws NoSuchFieldException 715 * if the field can not be found. 716 * @see #getDeclaredField(String) 717 */ 718 public Field getField(String name) throws NoSuchFieldException { 719 if (name == null) { 720 throw new NullPointerException("name == null"); 721 } 722 Field result = getPublicFieldRecursive(name); 723 if (result == null) { 724 throw new NoSuchFieldException(name); 725 } 726 return result; 727 } 728 729 private Field getPublicFieldRecursive(String name) { 730 // search superclasses 731 for (Class<?> c = this; c != null; c = c.getSuperclass()) { 732 Field result = Class.getDeclaredField(c, name); 733 if (result != null && (result.getModifiers() & Modifier.PUBLIC) != 0) { 734 return result; 735 } 736 } 737 738 // search implemented interfaces 739 for (Class<?> c = this; c != null; c = c.getSuperclass()) { 740 for (Class<?> ifc : c.getInterfaces()) { 741 Field result = ifc.getPublicFieldRecursive(name); 742 if (result != null && (result.getModifiers() & Modifier.PUBLIC) != 0) { 743 return result; 744 } 745 } 746 } 747 748 return null; 749 } 750 751 /** 752 * Returns an array containing {@code Field} objects for all public fields 753 * for the class C represented by this {@code Class}. Fields may be declared 754 * in C, the interfaces it implements or in the superclasses of C. The 755 * elements in the returned array are in no particular order. 756 * 757 * <p>If there are no public fields or if this class represents an array class, 758 * a primitive type or {@code void} then an empty array is returned. 759 * 760 * @see #getDeclaredFields() 761 */ 762 public Field[] getFields() { 763 List<Field> fields = new ArrayList<Field>(); 764 getPublicFieldsRecursive(fields); 765 766 /* 767 * The result may include duplicates when this class implements an interface 768 * through multiple paths. Remove those duplicates. 769 */ 770 CollectionUtils.removeDuplicates(fields, Field.ORDER_BY_NAME_AND_DECLARING_CLASS); 771 return fields.toArray(new Field[fields.size()]); 772 } 773 774 /** 775 * Populates {@code result} with public fields defined by this class, its 776 * superclasses, and all implemented interfaces. 777 */ 778 private void getPublicFieldsRecursive(List<Field> result) { 779 // search superclasses 780 for (Class<?> c = this; c != null; c = c.getSuperclass()) { 781 for (Field field : Class.getDeclaredFields(c, true)) { 782 result.add(field); 783 } 784 } 785 786 // search implemented interfaces 787 for (Class<?> c = this; c != null; c = c.getSuperclass()) { 788 for (Class<?> ifc : c.getInterfaces()) { 789 ifc.getPublicFieldsRecursive(result); 790 } 791 } 792 } 793 794 /** 795 * Returns the {@link Type}s of the interfaces that this {@code Class} directly 796 * implements. If the {@code Class} represents a primitive type or {@code 797 * void} then an empty array is returned. 798 */ 799 public Type[] getGenericInterfaces() { 800 Type[] result; 801 synchronized (Caches.genericInterfaces) { 802 result = Caches.genericInterfaces.get(this); 803 if (result == null) { 804 String annotationSignature = AnnotationAccess.getSignature(this); 805 if (annotationSignature == null) { 806 result = getInterfaces(); 807 } else { 808 GenericSignatureParser parser = new GenericSignatureParser(getClassLoader()); 809 parser.parseForClass(this, annotationSignature); 810 result = Types.getTypeArray(parser.interfaceTypes, false); 811 } 812 Caches.genericInterfaces.put(this, result); 813 } 814 } 815 return (result.length == 0) ? result : result.clone(); 816 } 817 818 /** 819 * Returns the {@code Type} that represents the superclass of this {@code 820 * class}. 821 */ 822 public Type getGenericSuperclass() { 823 Type genericSuperclass = getSuperclass(); 824 String annotationSignature = AnnotationAccess.getSignature(this); 825 if (annotationSignature != null) { 826 GenericSignatureParser parser = new GenericSignatureParser(getClassLoader()); 827 parser.parseForClass(this, annotationSignature); 828 genericSuperclass = parser.superclassType; 829 } 830 return Types.getType(genericSuperclass); 831 } 832 833 /** 834 * Returns an array of {@code Class} objects that match the interfaces 835 * in the {@code implements} declaration of the class represented 836 * by this {@code Class}. The order of the elements in the array is 837 * identical to the order in the original class declaration. If the class 838 * does not implement any interfaces, an empty array is returned. 839 */ 840 public native Class<?>[] getInterfaces(); 841 842 /** 843 * Returns a {@code Method} object which represents the public method with 844 * the given name and parameter types. 845 * {@code (Class[]) null} is equivalent to the empty array. 846 * 847 * <p>This method first searches the class C represented by this {@code Class}, 848 * then the superclasses of C, 849 * and finally the interfaces implemented by C and its superclasses. 850 * 851 * <p>Use {@link #getDeclaredMethod} if you don't want to search superclasses. 852 * 853 * @throws NoSuchMethodException 854 * if the method can not be found. 855 */ 856 public Method getMethod(String name, Class<?>... parameterTypes) throws NoSuchMethodException { 857 Member member = getConstructorOrMethod(name, true, true, parameterTypes); 858 if (member instanceof Constructor) { 859 throw new NoSuchMethodException(name); 860 } 861 return (Method) member; 862 } 863 864 /** 865 * Returns an array containing {@code Method} objects for all public methods 866 * for the class C represented by this {@code Class}. Methods may be 867 * declared in C, the interfaces it implements or in the superclasses of C. 868 * The elements in the returned array are in no particular order. 869 * 870 * <p>If there are no public methods or if this {@code Class} represents a 871 * primitive type or {@code void} then an empty array is returned. 872 * 873 * @see #getDeclaredMethods() 874 */ 875 public Method[] getMethods() { 876 List<Method> methods = new ArrayList<Method>(); 877 getPublicMethodsRecursive(methods); 878 879 /* 880 * Remove methods defined by multiple types, preferring to keep methods 881 * declared by derived types. 882 */ 883 CollectionUtils.removeDuplicates(methods, Method.ORDER_BY_SIGNATURE); 884 return methods.toArray(new Method[methods.size()]); 885 } 886 887 /** 888 * Populates {@code result} with public methods defined by this class, its 889 * superclasses, and all implemented interfaces, including overridden methods. 890 */ 891 private void getPublicMethodsRecursive(List<Method> result) { 892 // search superclasses 893 for (Class<?> c = this; c != null; c = c.getSuperclass()) { 894 for (Method method : Class.getDeclaredMethods(c, true)) { 895 result.add(method); 896 } 897 } 898 899 // search implemented interfaces 900 for (Class<?> c = this; c != null; c = c.getSuperclass()) { 901 for (Class<?> ifc : c.getInterfaces()) { 902 ifc.getPublicMethodsRecursive(result); 903 } 904 } 905 } 906 907 /** 908 * Returns an integer that represents the modifiers of the class represented 909 * by this {@code Class}. The returned value is a combination of bits 910 * defined by constants in the {@link Modifier} class. 911 */ 912 public int getModifiers() { 913 return getModifiers(this, false); 914 } 915 916 /* 917 * Returns the modifiers for the given class. 918 * 919 * {@code ignoreInnerClassesAttrib} determines whether we look for and use the 920 * flags from an "inner class" attribute 921 */ 922 private static native int getModifiers(Class<?> clazz, boolean ignoreInnerClassesAttrib); 923 924 /** 925 * Returns the name of the class represented by this {@code Class}. For a 926 * description of the format which is used, see the class definition of 927 * {@link Class}. 928 */ 929 public String getName() { 930 String result = name; 931 return (result == null) ? (name = getNameNative()) : result; 932 } 933 934 private native String getNameNative(); 935 936 /** 937 * Returns the simple name of the class represented by this {@code Class} as 938 * defined in the source code. If there is no name (that is, the class is 939 * anonymous) then an empty string is returned. If the receiver is an array 940 * then the name of the underlying type with square braces appended (for 941 * example {@code "Integer[]"}) is returned. 942 * 943 * @return the simple name of the class represented by this {@code Class}. 944 */ 945 public String getSimpleName() { 946 if (isArray()) { 947 return getComponentType().getSimpleName() + "[]"; 948 } 949 950 String name = getName(); 951 952 if (isAnonymousClass()) { 953 return ""; 954 } 955 956 if (isMemberClass() || isLocalClass()) { 957 return getInnerClassName(); 958 } 959 960 int dot = name.lastIndexOf('.'); 961 if (dot != -1) { 962 return name.substring(dot + 1); 963 } 964 965 return name; 966 } 967 968 /* 969 * Returns the simple name of a member or local class, or null otherwise. 970 */ 971 private native String getInnerClassName(); 972 973 /** 974 * Returns null. 975 */ 976 public ProtectionDomain getProtectionDomain() { 977 return null; 978 } 979 980 /** 981 * Returns the URL of the given resource, or null if the resource is not found. 982 * The mapping between the resource name and the URL is managed by the class' class loader. 983 * 984 * @see ClassLoader 985 */ 986 public URL getResource(String resourceName) { 987 // Get absolute resource name, but without the leading slash 988 if (resourceName.startsWith("/")) { 989 resourceName = resourceName.substring(1); 990 } else { 991 String pkg = getName(); 992 int dot = pkg.lastIndexOf('.'); 993 if (dot != -1) { 994 pkg = pkg.substring(0, dot).replace('.', '/'); 995 } else { 996 pkg = ""; 997 } 998 999 resourceName = pkg + "/" + resourceName; 1000 } 1001 1002 // Delegate to proper class loader 1003 ClassLoader loader = getClassLoader(); 1004 if (loader != null) { 1005 return loader.getResource(resourceName); 1006 } else { 1007 return ClassLoader.getSystemResource(resourceName); 1008 } 1009 } 1010 1011 /** 1012 * Returns a read-only stream for the contents of the given resource, or null if the resource 1013 * is not found. 1014 * The mapping between the resource name and the stream is managed by the class' class loader. 1015 * 1016 * @see ClassLoader 1017 */ 1018 public InputStream getResourceAsStream(String resourceName) { 1019 // Get absolute resource name, but without the leading slash 1020 if (resourceName.startsWith("/")) { 1021 resourceName = resourceName.substring(1); 1022 } else { 1023 String pkg = getName(); 1024 int dot = pkg.lastIndexOf('.'); 1025 if (dot != -1) { 1026 pkg = pkg.substring(0, dot).replace('.', '/'); 1027 } else { 1028 pkg = ""; 1029 } 1030 1031 resourceName = pkg + "/" + resourceName; 1032 } 1033 1034 // Delegate to proper class loader 1035 ClassLoader loader = getClassLoader(); 1036 if (loader != null) { 1037 return loader.getResourceAsStream(resourceName); 1038 } else { 1039 return ClassLoader.getSystemResourceAsStream(resourceName); 1040 } 1041 } 1042 1043 /** 1044 * Returns null. (On Android, a {@code ClassLoader} can load classes from multiple dex files. 1045 * All classes from any given dex file will have the same signers, but different dex 1046 * files may have different signers. This does not fit well with the original 1047 * {@code ClassLoader}-based model of {@code getSigners}.) 1048 */ 1049 public Object[] getSigners() { 1050 // See http://code.google.com/p/android/issues/detail?id=1766. 1051 return null; 1052 } 1053 1054 /** 1055 * Returns the {@code Class} object which represents the superclass of the 1056 * class represented by this {@code Class}. If this {@code Class} represents 1057 * the {@code Object} class, a primitive type, an interface or void then the 1058 * method returns {@code null}. If this {@code Class} represents an array 1059 * class then the {@code Object} class is returned. 1060 */ 1061 public native Class<? super T> getSuperclass(); 1062 1063 /** 1064 * Returns an array containing {@code TypeVariable} objects for type 1065 * variables declared by the generic class represented by this {@code 1066 * Class}. Returns an empty array if the class is not generic. 1067 */ 1068 @SuppressWarnings("unchecked") 1069 public synchronized TypeVariable<Class<T>>[] getTypeParameters() { 1070 String annotationSignature = AnnotationAccess.getSignature(this); 1071 if (annotationSignature == null) { 1072 return EmptyArray.TYPE_VARIABLE; 1073 } 1074 GenericSignatureParser parser = new GenericSignatureParser(getClassLoader()); 1075 parser.parseForClass(this, annotationSignature); 1076 return parser.formalTypeParameters; 1077 } 1078 1079 /** 1080 * Tests whether this {@code Class} represents an annotation class. 1081 */ 1082 public boolean isAnnotation() { 1083 final int ACC_ANNOTATION = 0x2000; // not public in reflect.Modifiers 1084 int mod = getModifiers(this, true); 1085 return (mod & ACC_ANNOTATION) != 0; 1086 } 1087 1088 @Override public boolean isAnnotationPresent(Class<? extends Annotation> annotationType) { 1089 if (annotationType == null) { 1090 throw new NullPointerException("annotationType == null"); 1091 } 1092 1093 if (isDeclaredAnnotationPresent(annotationType)) { 1094 return true; 1095 } 1096 1097 if (annotationType.isDeclaredAnnotationPresent(Inherited.class)) { 1098 for (Class<?> sup = getSuperclass(); sup != null; sup = sup.getSuperclass()) { 1099 if (sup.isDeclaredAnnotationPresent(annotationType)) { 1100 return true; 1101 } 1102 } 1103 } 1104 1105 return false; 1106 } 1107 1108 /** 1109 * Tests whether the class represented by this {@code Class} is 1110 * anonymous. 1111 */ 1112 native public boolean isAnonymousClass(); 1113 1114 /** 1115 * Tests whether the class represented by this {@code Class} is an array class. 1116 */ 1117 public boolean isArray() { 1118 return getComponentType() != null; 1119 } 1120 1121 /** 1122 * Tests whether the given class type can be converted to the class 1123 * represented by this {@code Class}. Conversion may be done via an identity 1124 * conversion or a widening reference conversion (if either the receiver or 1125 * the argument represent primitive types, only the identity conversion 1126 * applies). 1127 * 1128 * @throws NullPointerException 1129 * if {@code c} is {@code null}. 1130 */ 1131 public native boolean isAssignableFrom(Class<?> c); 1132 1133 /** 1134 * Tests whether the class represented by this {@code Class} is an 1135 * {@code enum}. 1136 */ 1137 public boolean isEnum() { 1138 if (getSuperclass() != Enum.class) { 1139 return false; 1140 } 1141 int mod = getModifiers(this, true); 1142 return (mod & 0x4000) != 0; 1143 } 1144 1145 /** 1146 * Tests whether the given object can be cast to the class 1147 * represented by this {@code Class}. This is the runtime version of the 1148 * {@code instanceof} operator. 1149 * 1150 * @return {@code true} if {@code object} can be cast to the type 1151 * represented by this {@code Class}; {@code false} if {@code 1152 * object} is {@code null} or cannot be cast. 1153 */ 1154 public native boolean isInstance(Object object); 1155 1156 /** 1157 * Tests whether this {@code Class} represents an interface. 1158 */ 1159 public native boolean isInterface(); 1160 1161 /** 1162 * Tests whether the class represented by this {@code Class} is defined 1163 * locally. 1164 */ 1165 public boolean isLocalClass() { 1166 boolean enclosed = (getEnclosingMethod() != null || 1167 getEnclosingConstructor() != null); 1168 return enclosed && !isAnonymousClass(); 1169 } 1170 1171 /** 1172 * Tests whether the class represented by this {@code Class} is a member 1173 * class. 1174 */ 1175 public boolean isMemberClass() { 1176 return getDeclaringClass() != null; 1177 } 1178 1179 /** 1180 * Tests whether this {@code Class} represents a primitive type. 1181 */ 1182 public native boolean isPrimitive(); 1183 1184 /** 1185 * Tests whether this {@code Class} represents a synthetic type. 1186 */ 1187 public boolean isSynthetic() { 1188 final int ACC_SYNTHETIC = 0x1000; // not public in reflect.Modifiers 1189 int mod = getModifiers(this, true); 1190 return (mod & ACC_SYNTHETIC) != 0; 1191 } 1192 1193 /** 1194 * Returns a new instance of the class represented by this {@code Class}, 1195 * created by invoking the default (that is, zero-argument) constructor. If 1196 * there is no such constructor, or if the creation fails (either because of 1197 * a lack of available memory or because an exception is thrown by the 1198 * constructor), an {@code InstantiationException} is thrown. If the default 1199 * constructor exists but is not accessible from the context where this 1200 * method is invoked, an {@code IllegalAccessException} is thrown. 1201 * 1202 * @throws IllegalAccessException 1203 * if the default constructor is not visible. 1204 * @throws InstantiationException 1205 * if the instance can not be created. 1206 */ 1207 public T newInstance() throws InstantiationException, IllegalAccessException { 1208 return newInstanceImpl(); 1209 } 1210 1211 private native T newInstanceImpl() throws IllegalAccessException, InstantiationException; 1212 1213 @Override 1214 public String toString() { 1215 if (isPrimitive()) { 1216 return getSimpleName(); 1217 } 1218 return (isInterface() ? "interface " : "class ") + getName(); 1219 } 1220 1221 /** 1222 * Returns the {@code Package} of which the class represented by this 1223 * {@code Class} is a member. Returns {@code null} if no {@code Package} 1224 * object was created by the class loader of the class. 1225 */ 1226 public Package getPackage() { 1227 // TODO This might be a hack, but the VM doesn't have the necessary info. 1228 ClassLoader loader = getClassLoader(); 1229 if (loader != null) { 1230 String name = getName(); 1231 int dot = name.lastIndexOf('.'); 1232 return (dot != -1 ? loader.getPackage(name.substring(0, dot)) : null); 1233 } 1234 return null; 1235 } 1236 1237 /** 1238 * Returns the assertion status for the class represented by this {@code 1239 * Class}. Assertion is enabled / disabled based on the class loader, 1240 * package or class default at runtime. 1241 */ 1242 public native boolean desiredAssertionStatus(); 1243 1244 /** 1245 * Casts this {@code Class} to represent a subclass of the given class. 1246 * If successful, this {@code Class} is returned; otherwise a {@code 1247 * ClassCastException} is thrown. 1248 * 1249 * @throws ClassCastException 1250 * if this {@code Class} cannot be cast to the given type. 1251 */ 1252 @SuppressWarnings("unchecked") 1253 public <U> Class<? extends U> asSubclass(Class<U> c) { 1254 if (c.isAssignableFrom(this)) { 1255 return (Class<? extends U>)this; 1256 } 1257 String actualClassName = this.getName(); 1258 String desiredClassName = c.getName(); 1259 throw new ClassCastException(actualClassName + " cannot be cast to " + desiredClassName); 1260 } 1261 1262 /** 1263 * Casts the given object to the type represented by this {@code Class}. 1264 * If the object is {@code null} then the result is also {@code null}. 1265 * 1266 * @throws ClassCastException 1267 * if the object cannot be cast to the given type. 1268 */ 1269 @SuppressWarnings("unchecked") 1270 public T cast(Object obj) { 1271 if (obj == null) { 1272 return null; 1273 } else if (this.isInstance(obj)) { 1274 return (T)obj; 1275 } 1276 String actualClassName = obj.getClass().getName(); 1277 String desiredClassName = this.getName(); 1278 throw new ClassCastException(actualClassName + " cannot be cast to " + desiredClassName); 1279 } 1280 1281 /** 1282 * Copies two arrays into one. Assumes that the destination array is large 1283 * enough. 1284 * 1285 * @param result the destination array 1286 * @param head the first source array 1287 * @param tail the second source array 1288 * @return the destination array, that is, result 1289 */ 1290 private static <T extends Object> T[] arraycopy(T[] result, T[] head, T[] tail) { 1291 System.arraycopy(head, 0, result, 0, head.length); 1292 System.arraycopy(tail, 0, result, head.length, tail.length); 1293 return result; 1294 } 1295 1296 /** 1297 * The annotation directory offset of this class in its own Dex, or 0 if it 1298 * is unknown. 1299 * 1300 * TODO: 0 is a sentinel that means 'no annotations directory'; this should be -1 if unknown 1301 * 1302 * @hide 1303 */ 1304 public int getDexAnnotationDirectoryOffset() { 1305 Dex dex = getDex(); 1306 if (dex == null) { 1307 return 0; 1308 } 1309 int classDefIndex = getDexClassDefIndex(); 1310 if (classDefIndex < 0) { 1311 return 0; 1312 } 1313 return dex.annotationDirectoryOffsetFromClassDefIndex(classDefIndex); 1314 } 1315 1316 1317 /** 1318 * Returns a resolved type from the dex cache, computing the type from the dex file if 1319 * necessary. 1320 * TODO: use Dalvik's dex cache. 1321 * @hide 1322 */ 1323 public Class<?> getDexCacheType(Dex dex, int typeIndex) { 1324 String internalName = dex.typeNames().get(typeIndex); 1325 return InternalNames.getClass(getClassLoader(), internalName); 1326 } 1327 1328 /** 1329 * Returns a string from the dex cache, computing the string from the dex file if necessary. 1330 * 1331 * @hide 1332 */ 1333 public String getDexCacheString(Dex dex, int dexStringIndex) { 1334 return dex.strings().get(dexStringIndex); 1335 } 1336 1337 1338 private static class Caches { 1339 /** 1340 * Cache to avoid frequent recalculation of generic interfaces, which is generally uncommon. 1341 * Sized sufficient to allow ConcurrentHashMapTest to run without recalculating its generic 1342 * interfaces (required to avoid time outs). Validated by running reflection heavy code 1343 * such as applications using Guice-like frameworks. 1344 */ 1345 private static final BasicLruCache<Class, Type[]> genericInterfaces 1346 = new BasicLruCache<Class, Type[]>(8); 1347 } 1348} 1349