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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * Copyright (C) 2006-2007 The Android Open Source Project
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
24 * http://www.apache.org/licenses/LICENSE-2.0
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.
35 import dalvik.system.VMStack;
36 import java.io.InputStream;
37 import java.io.Serializable;
38 import static java.lang.ClassCache.*;
39 import java.lang.annotation.Annotation;
40 import java.lang.annotation.Inherited;
41 import java.lang.ref.SoftReference;
42 import java.lang.reflect.AccessibleObject;
43 import java.lang.reflect.AnnotatedElement;
44 import java.lang.reflect.Constructor;
45 import java.lang.reflect.Field;
46 import java.lang.reflect.GenericDeclaration;
47 import java.lang.reflect.Member;
48 import java.lang.reflect.Method;
49 import java.lang.reflect.Modifier;
50 import java.lang.reflect.Type;
51 import java.lang.reflect.TypeVariable;
53 import java.security.ProtectionDomain;
54 import java.util.Collection;
55 import java.util.HashMap;
56 import org.apache.harmony.kernel.vm.StringUtils;
57 import org.apache.harmony.luni.lang.reflect.GenericSignatureParser;
58 import org.apache.harmony.luni.lang.reflect.Types;
61 * The in-memory representation of a Java class. This representation serves as
62 * the starting point for querying class-related information, a process usually
63 * called "reflection". There are basically three types of {@code Class}
64 * instances: those representing real classes and interfaces, those representing
65 * primitive types, and those representing array classes.
67 * <h4>Class instances representing object types (classes or interfaces)</h4>
69 * These represent an ordinary class or interface as found in the class
70 * hierarchy. The name associated with these {@code Class} instances is simply
71 * the fully qualified class name of the class or interface that it represents.
72 * In addition to this human-readable name, each class is also associated by a
73 * so-called <em>signature</em>, which is the letter "L", followed by the
74 * class name and a semicolon (";"). The signature is what the runtime system
75 * uses internally for identifying the class (for example in a DEX file).
77 * <h4>Classes representing primitive types</h4>
79 * These represent the standard Java primitive types and hence share their
80 * names (for example "int" for the {@code int} primitive type). Although it is
81 * not possible to create new instances based on these {@code Class} instances,
82 * they are still useful for providing reflection information, and as the
83 * component type of array classes. There is one {@code Class} instance for each
84 * primitive type, and their signatures are:
87 * <li>{@code B} representing the {@code byte} primitive type</li>
88 * <li>{@code S} representing the {@code short} primitive type</li>
89 * <li>{@code I} representing the {@code int} primitive type</li>
90 * <li>{@code J} representing the {@code long} primitive type</li>
91 * <li>{@code F} representing the {@code float} primitive type</li>
92 * <li>{@code D} representing the {@code double} primitive type</li>
93 * <li>{@code C} representing the {@code char} primitive type</li>
94 * <li>{@code Z} representing the {@code boolean} primitive type</li>
95 * <li>{@code V} representing void function return values</li>
98 * <h4>Classes representing array classes</h4>
100 * These represent the classes of Java arrays. There is one such {@code Class}
101 * instance per combination of array leaf component type and arity (number of
102 * dimensions). In this case, the name associated with the {@code Class}
103 * consists of one or more left square brackets (one per dimension in the array)
104 * followed by the signature of the class representing the leaf component type,
105 * which can be either an object type or a primitive type. The signature of a
106 * {@code Class} representing an array type is the same as its name. Examples
107 * of array class signatures are:
110 * <li>{@code [I} representing the {@code int[]} type</li>
111 * <li>{@code [Ljava/lang/String;} representing the {@code String[]} type</li>
112 * <li>{@code [[[C} representing the {@code char[][][]} type (three dimensions!)</li>
115 public final class Class<T> implements Serializable, AnnotatedElement, GenericDeclaration, Type {
117 private static final long serialVersionUID = 3206093459760846163L;
120 * This field is initialized by dalvikvm when the class is loaded.
122 private transient ProtectionDomain pd;
125 * null-ok; cache of reflective information, wrapped in a soft
128 private transient volatile SoftReference<ClassCache<T>> cacheRef;
131 * Lazily computed name of this class; always prefer calling getName().
133 private transient String name;
136 // Prevent this class to be instantiated, instance
137 // should be created by JVM only
141 * Get the Signature attribute for this class. Returns null if not found.
143 private String getSignatureAttribute() {
144 Object[] annotation = getSignatureAnnotation();
146 if (annotation == null) {
150 return StringUtils.combineStrings(annotation);
154 * Get the Signature annotation for this class. Returns null if not found.
156 native private Object[] getSignatureAnnotation();
159 * Returns a {@code Class} object which represents the class with the
160 * specified name. The name should be the name of a class as described in
161 * the {@link Class class definition}; however, {@code Class}es representing
162 * primitive types can not be found using this method.
164 * If the class has not been loaded so far, it is being loaded and linked
165 * first. This is done through either the class loader of the calling class
166 * or one of its parent class loaders. The class is also being initialized,
167 * which means that a possible static initializer block is executed.
170 * the name of the non-primitive-type class to find.
171 * @return the named {@code Class} instance.
172 * @throws ClassNotFoundException
173 * if the requested class can not be found.
174 * @throws LinkageError
175 * if an error occurs during linkage
176 * @throws ExceptionInInitializerError
177 * if an exception occurs during static initialization of a
180 public static Class<?> forName(String className) throws ClassNotFoundException {
181 return forName(className, true, VMStack.getCallingClassLoader());
185 * Returns a {@code Class} object which represents the class with the
186 * specified name. The name should be the name of a class as described in
187 * the {@link Class class definition}, however {@code Class}es representing
188 * primitive types can not be found using this method. Security rules will
191 * If the class has not been loaded so far, it is being loaded and linked
192 * first. This is done through either the specified class loader or one of
193 * its parent class loaders. The caller can also request the class to be
194 * initialized, which means that a possible static initializer block is
198 * the name of the non-primitive-type class to find.
199 * @param initializeBoolean
200 * indicates whether the class should be initialized.
202 * the class loader to use to load the class.
203 * @return the named {@code Class} instance.
204 * @throws ClassNotFoundException
205 * if the requested class can not be found.
206 * @throws LinkageError
207 * if an error occurs during linkage
208 * @throws ExceptionInInitializerError
209 * if an exception occurs during static initialization of a
212 public static Class<?> forName(String className, boolean initializeBoolean,
213 ClassLoader classLoader) throws ClassNotFoundException {
215 if (classLoader == null) {
216 SecurityManager smgr = System.getSecurityManager();
218 ClassLoader calling = VMStack.getCallingClassLoader();
219 if (calling != null) {
220 smgr.checkPermission(new RuntimePermission("getClassLoader"));
224 classLoader = ClassLoader.getSystemClassLoader();
226 // Catch an Exception thrown by the underlying native code. It wraps
227 // up everything inside a ClassNotFoundException, even if e.g. an
228 // Error occurred during initialization. This as a workaround for
229 // an ExceptionInInitilaizerError that's also wrapped. It is actually
230 // expected to be thrown. Maybe the same goes for other errors.
231 // Not wrapping up all the errors will break android though.
234 result = classForName(className, initializeBoolean,
236 } catch (ClassNotFoundException e) {
237 Throwable cause = e.getCause();
238 if (cause instanceof ExceptionInInitializerError) {
239 throw (ExceptionInInitializerError) cause;
247 * Returns a class by name without any security checks.
249 * @param className The name of the non-primitive type class to find
250 * @param initializeBoolean A boolean indicating whether the class should be
252 * @param classLoader The class loader to use to load the class
253 * @return the named class.
254 * @throws ClassNotFoundException If the class could not be found
256 static native Class<?> classForName(String className, boolean initializeBoolean,
257 ClassLoader classLoader) throws ClassNotFoundException;
260 * Returns an array containing {@code Class} objects for all public classes
261 * and interfaces that are members of this class. This includes public
262 * members inherited from super classes and interfaces. If there are no such
263 * class members or if this object represents a primitive type then an array
264 * of length 0 is returned.
266 * @return the public class members of the class represented by this object.
267 * @throws SecurityException
268 * if a security manager exists and it does not allow member
271 public Class<?>[] getClasses() {
272 checkPublicMemberAccess();
273 return getFullListOfClasses(true);
277 * Returns the annotation of the given type. If there is no such annotation
278 * then the method returns {@code null}.
280 * @param annotationClass
281 * the annotation type.
282 * @return the annotation of the given type, or {@code null} if there is no
285 @SuppressWarnings("unchecked")
286 public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
287 Annotation[] list = getAnnotations();
288 for (int i = 0; i < list.length; i++) {
289 if (annotationClass.isInstance(list[i])) {
298 * Returns all the annotations of this class. If there are no annotations
299 * then an empty array is returned.
301 * @return a copy of the array containing this class' annotations.
302 * @see #getDeclaredAnnotations()
304 public Annotation[] getAnnotations() {
306 * We need to get the annotations declared on this class, plus the
307 * annotations from superclasses that have the "@Inherited" annotation
308 * set. We create a temporary map to use while we accumulate the
309 * annotations and convert it to an array at the end.
311 * It's possible to have duplicates when annotations are inherited.
312 * We use a Map to filter those out.
314 * HashMap might be overkill here.
316 HashMap<Class, Annotation> map = new HashMap<Class, Annotation>();
317 Annotation[] annos = getDeclaredAnnotations();
319 for (int i = annos.length-1; i >= 0; --i)
320 map.put(annos[i].annotationType(), annos[i]);
322 for (Class sup = getSuperclass(); sup != null;
323 sup = sup.getSuperclass()) {
324 annos = sup.getDeclaredAnnotations();
325 for (int i = annos.length-1; i >= 0; --i) {
326 Class clazz = annos[i].annotationType();
327 if (!map.containsKey(clazz) &&
328 clazz.isAnnotationPresent(Inherited.class)) {
329 map.put(clazz, annos[i]);
334 /* convert annotation values from HashMap to array */
335 Collection<Annotation> coll = map.values();
336 return coll.toArray(new Annotation[coll.size()]);
340 * Returns the canonical name of this class. If this class does not have a
341 * canonical name as defined in the Java Language Specification, then the
342 * method returns {@code null}.
344 * @return this class' canonical name, or {@code null} if it does not have a
347 public String getCanonicalName() {
348 if (isLocalClass() || isAnonymousClass())
353 * The canonical name of an array type depends on the (existence of)
354 * the component type's canonical name.
356 String name = getComponentType().getCanonicalName();
360 } else if (isMemberClass()) {
362 * The canonical name of an inner class depends on the (existence
363 * of) the declaring class' canonical name.
365 String name = getDeclaringClass().getCanonicalName();
367 return name + "." + getSimpleName();
371 * The canonical name of a top-level class or primitive type is
372 * equal to the fully qualified name.
378 * Other classes don't have a canonical name.
384 * Returns the class loader which was used to load the class represented by
385 * this {@code Class}. Implementations are free to return {@code null} for
386 * classes that were loaded by the bootstrap class loader. The Android
387 * reference implementation, though, returns a reference to an actual
388 * representation of the bootstrap class loader.
390 * @return the class loader for the represented class.
391 * @throws SecurityException
392 * if a security manager exists and it does not allow accessing
396 public ClassLoader getClassLoader() {
397 SecurityManager smgr = System.getSecurityManager();
398 ClassLoader loader = getClassLoaderImpl();
399 if (smgr != null && loader != null) {
400 ClassLoader calling = VMStack.getCallingClassLoader();
402 if (calling != null && !calling.isAncestorOf(loader)) {
403 smgr.checkPermission(new RuntimePermission("getClassLoader"));
407 if (this.isPrimitive()) {
411 if (loader == null) {
412 loader = BootClassLoader.getInstance();
419 * This must be provided by the VM vendor, as it is used by other provided
420 * class implementations in this package. Outside of this class, it is used
421 * by SecurityManager.checkMemberAccess(), classLoaderDepth(),
422 * currentClassLoader() and currentLoadedClass(). Return the ClassLoader for
423 * this Class without doing any security checks. The bootstrap ClassLoader
424 * is returned, unlike getClassLoader() which returns null in place of the
425 * bootstrap ClassLoader.
427 * @return the ClassLoader
428 * @see ClassLoader#isSystemClassLoader()
430 ClassLoader getClassLoaderImpl() {
431 ClassLoader loader = getClassLoader(this);
432 return loader == null ? BootClassLoader.getInstance() : loader;
436 * Returns the defining class loader for the given class.
438 * @param clazz the class the class loader of which we want
439 * @return the class loader
441 private static native ClassLoader getClassLoader(Class<?> clazz);
444 * Returns a {@code Class} object which represents the component type if
445 * this class represents an array type. Returns {@code null} if this class
446 * does not represent an array type. The component type of an array type is
447 * the type of the elements of the array.
449 * @return the component type of this class.
451 public native Class<?> getComponentType();
454 * Returns a {@code Constructor} object which represents the public
455 * constructor matching the specified parameter types.
457 * @param parameterTypes
458 * the parameter types of the requested constructor.
459 * {@code (Class[]) null} is equivalent to the empty array.
460 * @return the constructor described by {@code parameterTypes}.
461 * @throws NoSuchMethodException
462 * if the constructor can not be found.
463 * @throws SecurityException
464 * if a security manager exists and it does not allow member
466 * @see #getDeclaredConstructor(Class[])
468 @SuppressWarnings("unchecked")
469 public Constructor<T> getConstructor(Class<?>... parameterTypes) throws NoSuchMethodException,
471 checkPublicMemberAccess();
472 return getMatchingConstructor(getDeclaredConstructors(this, true), parameterTypes);
476 * Returns an array containing {@code Constructor} objects for all public
477 * constructors for the class represented by this {@code Class}. If there
478 * are no public constructors or if this {@code Class} represents an array
479 * class, a primitive type or void then an empty array is returned.
481 * @return an array with the public constructors of the class represented by
482 * this {@code Class}.
483 * @throws SecurityException
484 * if a security manager exists and it does not allow member
486 * @see #getDeclaredConstructors()
488 public Constructor<?>[] getConstructors() throws SecurityException {
489 checkPublicMemberAccess();
490 return getDeclaredConstructors(this, true);
494 * Returns the annotations that are directly defined on the class
495 * represented by this {@code Class}. Annotations that are inherited are not
496 * included in the result. If there are no annotations at all, an empty
499 * @return a copy of the array containing the annotations defined for the
500 * class that this {@code Class} represents.
501 * @see #getAnnotations()
503 native public Annotation[] getDeclaredAnnotations();
506 * Returns an array containing {@code Class} objects for all classes and
507 * interfaces that are declared as members of the class which this {@code
508 * Class} represents. If there are no classes or interfaces declared or if
509 * this class represents an array class, a primitive type or void, then an
510 * empty array is returned.
512 * @return an array with {@code Class} objects for all the classes and
513 * interfaces that are used in member declarations.
514 * @throws SecurityException
515 * if a security manager exists and it does not allow member
518 public Class<?>[] getDeclaredClasses() throws SecurityException {
519 checkDeclaredMemberAccess();
520 return getDeclaredClasses(this, false);
524 * Returns the list of member classes without performing any security checks
525 * first. This includes the member classes inherited from superclasses. If no
526 * member classes exist at all, an empty array is returned.
528 * @param publicOnly reflects whether we want only public members or all of them
529 * @return the list of classes
531 private Class<?>[] getFullListOfClasses(boolean publicOnly) {
532 Class<?>[] result = getDeclaredClasses(this, publicOnly);
534 // Traverse all superclasses
535 Class<?> clazz = this.getSuperclass();
536 while (clazz != null) {
537 Class<?>[] temp = getDeclaredClasses(clazz, publicOnly);
538 if (temp.length != 0) {
539 result = arraycopy(new Class[result.length + temp.length], result, temp);
542 clazz = clazz.getSuperclass();
549 * Returns the list of member classes of the given class. No security checks
550 * are performed. If no members exist, an empty array is returned.
552 * @param clazz the class the members of which we want
553 * @param publicOnly reflects whether we want only public member or all of them
554 * @return the class' class members
556 native private static Class<?>[] getDeclaredClasses(Class<?> clazz,
560 * Returns a {@code Constructor} object which represents the constructor
561 * matching the specified parameter types that is declared by the class
562 * represented by this {@code Class}.
564 * @param parameterTypes
565 * the parameter types of the requested constructor.
566 * {@code (Class[]) null} is equivalent to the empty array.
567 * @return the constructor described by {@code parameterTypes}.
568 * @throws NoSuchMethodException
569 * if the requested constructor can not be found.
570 * @throws SecurityException
571 * if a security manager exists and it does not allow member
573 * @see #getConstructor(Class[])
575 @SuppressWarnings("unchecked")
576 public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
577 throws NoSuchMethodException, SecurityException {
578 checkDeclaredMemberAccess();
579 return getMatchingConstructor(getDeclaredConstructors(this, false), parameterTypes);
583 * Returns an array containing {@code Constructor} objects for all
584 * constructors declared in the class represented by this {@code Class}. If
585 * there are no constructors or if this {@code Class} represents an array
586 * class, a primitive type or void then an empty array is returned.
588 * @return an array with the constructors declared in the class represented
589 * by this {@code Class}.
591 * @throws SecurityException
592 * if a security manager exists and it does not allow member
594 * @see #getConstructors()
596 public Constructor<?>[] getDeclaredConstructors() throws SecurityException {
597 checkDeclaredMemberAccess();
598 return getDeclaredConstructors(this, false);
602 * Returns the list of constructors without performing any security checks
603 * first. If no constructors exist, an empty array is returned.
605 * @param clazz the class of interest
606 * @param publicOnly reflects whether we want only public constructors or all of them
607 * @return the list of constructors
609 private static native <T> Constructor<T>[] getDeclaredConstructors(Class<T> clazz, boolean publicOnly);
612 * Finds a constructor with a given signature.
614 * @param list the list of constructors to search through
615 * @param parameterTypes the formal parameter list
616 * @return the matching constructor
617 * @throws NoSuchMethodException if the constructor does not exist.
619 private Constructor<T> getMatchingConstructor(
620 Constructor<T>[] list, Class<?>[] parameterTypes)
621 throws NoSuchMethodException {
622 for (int i = 0; i < list.length; i++) {
623 if (compareClassLists(list[i].getParameterTypes(), parameterTypes)) {
628 // BEGIN android-changed
629 StringBuilder sb = new StringBuilder();
630 sb.append(getSimpleName());
632 boolean first = true;
633 if (parameterTypes != null) {
634 for (Class<?> p : parameterTypes) {
639 sb.append(p.getSimpleName());
643 throw new NoSuchMethodException(sb.toString());
644 // END android-changed
648 * Returns a {@code Field} object for the field with the specified name
649 * which is declared in the class represented by this {@code Class}.
652 * the name of the requested field.
653 * @return the requested field in the class represented by this class.
654 * @throws NoSuchFieldException
655 * if the requested field can not be found.
656 * @throws SecurityException
657 * if a security manager exists and it does not allow member
659 * @see #getField(String)
661 public Field getDeclaredField(String name)
662 throws NoSuchFieldException, SecurityException {
663 checkDeclaredMemberAccess();
665 Field[] fields = getClassCache().getDeclaredFields();
666 Field field = findFieldByName(fields, name);
669 * Make a copy of the private (to the package) object, so that
670 * setAccessible() won't alter the private instance.
672 return REFLECT.clone(field);
676 * Returns an array containing {@code Field} objects for all fields declared
677 * in the class represented by this {@code Class}. If there are no fields or
678 * if this {@code Class} represents an array class, a primitive type or void
679 * then an empty array is returned.
681 * @return an array with the fields declared in the class represented by
683 * @throws SecurityException
684 * if a security manager exists and it does not allow member
688 public Field[] getDeclaredFields() throws SecurityException {
689 checkDeclaredMemberAccess();
691 // Return a copy of the private (to the package) array.
692 Field[] fields = getClassCache().getDeclaredFields();
693 return ClassCache.deepCopy(fields);
697 * Returns the list of fields without performing any security checks
698 * first. If no fields exist at all, an empty array is returned.
700 * @param clazz the class of interest
701 * @param publicOnly reflects whether we want only public fields or all of them
702 * @return the list of fields
704 static native Field[] getDeclaredFields(Class<?> clazz, boolean publicOnly);
707 * Returns a {@code Method} object which represents the method matching the
708 * specified name and parameter types that is declared by the class
709 * represented by this {@code Class}.
712 * the requested method's name.
713 * @param parameterTypes
714 * the parameter types of the requested method.
715 * {@code (Class[]) null} is equivalent to the empty array.
716 * @return the method described by {@code name} and {@code parameterTypes}.
717 * @throws NoSuchMethodException
718 * if the requested constructor can not be found.
719 * @throws NullPointerException
720 * if {@code name} is {@code null}.
721 * @throws SecurityException
722 * if a security manager exists and it does not allow member
724 * @see #getMethod(String, Class[])
726 public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
727 throws NoSuchMethodException, SecurityException {
728 checkDeclaredMemberAccess();
730 Method[] methods = getClassCache().getDeclaredMethods();
731 Method method = findMethodByName(methods, name, parameterTypes);
734 * Make a copy of the private (to the package) object, so that
735 * setAccessible() won't alter the private instance.
737 return REFLECT.clone(method);
741 * Returns an array containing {@code Method} objects for all methods
742 * declared in the class represented by this {@code Class}. If there are no
743 * methods or if this {@code Class} represents an array class, a primitive
744 * type or void then an empty array is returned.
746 * @return an array with the methods declared in the class represented by
747 * this {@code Class}.
748 * @throws SecurityException
749 * if a security manager exists and it does not allow member
753 public Method[] getDeclaredMethods() throws SecurityException {
754 checkDeclaredMemberAccess();
756 // Return a copy of the private (to the package) array.
757 Method[] methods = getClassCache().getDeclaredMethods();
758 return ClassCache.deepCopy(methods);
762 * Returns the list of methods without performing any security checks
763 * first. If no methods exist, an empty array is returned.
765 static native Method[] getDeclaredMethods(Class<?> clazz, boolean publicOnly);
768 * Gets the {@link ClassCache} for this instance.
770 * @return non-null; the cache object
772 /*package*/ ClassCache<T> getClassCache() {
774 * Note: It is innocuous if two threads try to simultaneously
775 * create the cache, so we don't bother protecting against that.
777 ClassCache<T> cache = null;
779 if (cacheRef != null) {
780 cache = cacheRef.get();
784 cache = new ClassCache<T>(this);
785 cacheRef = new SoftReference<ClassCache<T>>(cache);
792 * Returns the declaring {@code Class} of this {@code Class}. Returns
793 * {@code null} if the class is not a member of another class or if this
794 * {@code Class} represents an array class, a primitive type or void.
796 * @return the declaring {@code Class} or {@code null}.
798 native public Class<?> getDeclaringClass();
801 * Returns the enclosing {@code Class} of this {@code Class}. If there is no
802 * enclosing class the method returns {@code null}.
804 * @return the enclosing {@code Class} or {@code null}.
806 native public Class<?> getEnclosingClass();
809 * Gets the enclosing {@code Constructor} of this {@code Class}, if it is an
810 * anonymous or local/automatic class; otherwise {@code null}.
812 * @return the enclosing {@code Constructor} instance or {@code null}.
814 native public Constructor<?> getEnclosingConstructor();
817 * Gets the enclosing {@code Method} of this {@code Class}, if it is an
818 * anonymous or local/automatic class; otherwise {@code null}.
820 * @return the enclosing {@code Method} instance or {@code null}.
822 native public Method getEnclosingMethod();
825 * Gets the {@code enum} constants associated with this {@code Class}.
826 * Returns {@code null} if this {@code Class} does not represent an {@code
829 * @return an array with the {@code enum} constants or {@code null}.
831 @SuppressWarnings("unchecked")
832 public T[] getEnumConstants() {
834 checkPublicMemberAccess();
835 T[] values = getClassCache().getEnumValuesInOrder();
837 // Copy the private (to the package) array.
838 return (T[]) values.clone();
845 * Returns a {@code Field} object which represents the public field with the
846 * specified name. This method first searches the class C represented by
847 * this {@code Class}, then the interfaces implemented by C and finally the
851 * the name of the requested field.
852 * @return the public field specified by {@code name}.
853 * @throws NoSuchFieldException
854 * if the field can not be found.
855 * @throws SecurityException
856 * if a security manager exists and it does not allow member
858 * @see #getDeclaredField(String)
860 public Field getField(String name) throws NoSuchFieldException, SecurityException {
861 checkPublicMemberAccess();
863 Field[] fields = getClassCache().getAllPublicFields();
864 Field field = findFieldByName(fields, name);
867 * Make a copy of the private (to the package) object, so that
868 * setAccessible() won't alter the private instance.
870 return REFLECT.clone(field);
874 * Returns an array containing {@code Field} objects for all public fields
875 * for the class C represented by this {@code Class}. Fields may be declared
876 * in C, the interfaces it implements or in the superclasses of C. The
877 * elements in the returned array are in no particular order.
879 * If there are no public fields or if this class represents an array class,
880 * a primitive type or {@code void} then an empty array is returned.
883 * @return an array with the public fields of the class represented by this
885 * @throws SecurityException
886 * if a security manager exists and it does not allow member
888 * @see #getDeclaredFields()
890 public Field[] getFields() throws SecurityException {
891 checkPublicMemberAccess();
893 // Return a copy of the private (to the package) array.
894 Field[] fields = getClassCache().getAllPublicFields();
895 return ClassCache.deepCopy(fields);
899 * Gets the {@link Type}s of the interfaces that this {@code Class} directly
900 * implements. If the {@code Class} represents a primitive type or {@code
901 * void} then an empty array is returned.
903 * @return an array of {@link Type} instances directly implemented by the
904 * class represented by this {@code class}.
906 public Type[] getGenericInterfaces() {
907 GenericSignatureParser parser = new GenericSignatureParser(getClassLoader());
908 parser.parseForClass(this, getSignatureAttribute());
909 return Types.getClonedTypeArray(parser.interfaceTypes);
913 * Gets the {@code Type} that represents the superclass of this {@code
916 * @return an instance of {@code Type} representing the superclass.
918 public Type getGenericSuperclass() {
919 GenericSignatureParser parser = new GenericSignatureParser(getClassLoader());
920 parser.parseForClass(this, getSignatureAttribute());
921 return Types.getType(parser.superclassType);
925 * Returns an array of {@code Class} objects that match the interfaces
926 * specified in the {@code implements} declaration of the class represented
927 * by this {@code Class}. The order of the elements in the array is
928 * identical to the order in the original class declaration. If the class
929 * does not implement any interfaces, an empty array is returned.
931 * @return an array with the interfaces of the class represented by this
934 public native Class<?>[] getInterfaces();
936 // Changed to raw type to be closer to the RI
938 * Returns a {@code Method} object which represents the public method with
939 * the specified name and parameter types. This method first searches the
940 * class C represented by this {@code Class}, then the superclasses of C and
941 * finally the interfaces implemented by C and finally the superclasses of C
942 * for a method with matching name.
945 * the requested method's name.
946 * @param parameterTypes
947 * the parameter types of the requested method.
948 * {@code (Class[]) null} is equivalent to the empty array.
949 * @return the public field specified by {@code name}.
950 * @throws NoSuchMethodException
951 * if the method can not be found.
952 * @throws SecurityException
953 * if a security manager exists and it does not allow member
955 * @see #getDeclaredMethod(String, Class[])
957 public Method getMethod(String name, Class<?>... parameterTypes) throws NoSuchMethodException,
959 checkPublicMemberAccess();
961 Method[] methods = getClassCache().getMethods();
962 Method method = findMethodByName(methods, name, parameterTypes);
965 * Make a copy of the private (to the package) object, so that
966 * setAccessible() won't alter the private instance.
968 return REFLECT.clone(method);
972 * Returns an array containing {@code Method} objects for all public methods
973 * for the class C represented by this {@code Class}. Methods may be
974 * declared in C, the interfaces it implements or in the superclasses of C.
975 * The elements in the returned array are in no particular order.
977 * If there are no public methods or if this {@code Class} represents a
978 * primitive type or {@code void} then an empty array is returned.
981 * @return an array with the methods of the class represented by this
983 * @throws SecurityException
984 * if a security manager exists and it does not allow member
986 * @see #getDeclaredMethods()
988 public Method[] getMethods() throws SecurityException {
989 checkPublicMemberAccess();
991 // Return a copy of the private (to the package) array.
992 Method[] methods = getClassCache().getMethods();
993 return ClassCache.deepCopy(methods);
997 * Performs the security checks regarding the access of a public
998 * member of this {@code Class}.
1000 * <p><b>Note:</b> Because of the {@code getCallingClassLoader2()}
1001 * check, this method must be called exactly one level deep into a
1002 * public method on this instance.</p>
1004 /*package*/ void checkPublicMemberAccess() {
1005 SecurityManager smgr = System.getSecurityManager();
1008 smgr.checkMemberAccess(this, Member.PUBLIC);
1010 ClassLoader calling = VMStack.getCallingClassLoader2();
1011 ClassLoader current = getClassLoader();
1013 if (calling != null && !calling.isAncestorOf(current)) {
1014 smgr.checkPackageAccess(this.getPackage().getName());
1020 * Performs the security checks regarding the access of a declared
1021 * member of this {@code Class}.
1023 * <p><b>Note:</b> Because of the {@code getCallingClassLoader2()}
1024 * check, this method must be called exactly one level deep into a
1025 * public method on this instance.</p>
1027 private void checkDeclaredMemberAccess() {
1028 SecurityManager smgr = System.getSecurityManager();
1030 smgr.checkMemberAccess(this, Member.DECLARED);
1032 ClassLoader calling = VMStack.getCallingClassLoader2();
1033 ClassLoader current = getClassLoader();
1035 if (calling != null && !calling.isAncestorOf(current)) {
1036 smgr.checkPackageAccess(this.getPackage().getName());
1042 * Returns an integer that represents the modifiers of the class represented
1043 * by this {@code Class}. The returned value is a combination of bits
1044 * defined by constants in the {@link Modifier} class.
1046 * @return the modifiers of the class represented by this {@code Class}.
1048 public int getModifiers() {
1049 return getModifiers(this, false);
1053 * Return the modifiers for the given class.
1055 * @param clazz the class of interest
1056 * @ignoreInnerClassesAttrib determines whether we look for and use the
1057 * flags from an "inner class" attribute
1059 private static native int getModifiers(Class<?> clazz, boolean ignoreInnerClassesAttrib);
1062 * Returns the name of the class represented by this {@code Class}. For a
1063 * description of the format which is used, see the class definition of
1066 * @return the name of the class represented by this {@code Class}.
1068 public String getName() {
1069 String result = name;
1070 return (result == null) ? (name = getNameNative()) : result;
1073 private native String getNameNative();
1076 * Returns the simple name of the class represented by this {@code Class} as
1077 * defined in the source code. If there is no name (that is, the class is
1078 * anonymous) then an empty string is returned. If the receiver is an array
1079 * then the name of the underlying type with square braces appended (for
1080 * example {@code "Integer[]"}) is returned.
1082 * @return the simple name of the class represented by this {@code Class}.
1084 public String getSimpleName() {
1086 return getComponentType().getSimpleName() + "[]";
1089 String name = getName();
1091 if (isAnonymousClass()) {
1095 if (isMemberClass() || isLocalClass()) {
1096 return getInnerClassName();
1099 int dot = name.lastIndexOf('.');
1101 return name.substring(dot + 1);
1108 * Returns the simple name of a member or local class, or null otherwise.
1112 private native String getInnerClassName();
1115 * Returns the {@code ProtectionDomain} of the class represented by this
1118 * Note: In order to conserve space in an embedded target like Android, we
1119 * allow this method to return {@code null} for classes in the system
1120 * protection domain (that is, for system classes). System classes are
1121 * always given full permissions (that is, AllPermission). This can not be
1122 * changed through the {@link java.security.Policy} class.
1125 * @return the {@code ProtectionDomain} of the class represented by this
1127 * @throws SecurityException
1128 * if a security manager exists and it does not allow member
1131 public ProtectionDomain getProtectionDomain() {
1132 SecurityManager smgr = System.getSecurityManager();
1134 // Security check is independent of calling class loader.
1135 smgr.checkPermission(new RuntimePermission("getProtectionDomain"));
1142 * Returns the URL of the resource specified by {@code resName}. The mapping
1143 * between the resource name and the URL is managed by the class' class
1147 * the name of the resource.
1148 * @return the requested resource's {@code URL} object or {@code null} if
1149 * the resource can not be found.
1152 public URL getResource(String resName) {
1153 // Get absolute resource name, but without the leading slash
1154 if (resName.startsWith("/")) {
1155 resName = resName.substring(1);
1157 String pkg = getName();
1158 int dot = pkg.lastIndexOf('.');
1160 pkg = pkg.substring(0, dot).replace('.', '/');
1165 resName = pkg + "/" + resName;
1168 // Delegate to proper class loader
1169 ClassLoader loader = getClassLoader();
1170 if (loader != null) {
1171 return loader.getResource(resName);
1173 return ClassLoader.getSystemResource(resName);
1178 * Returns a read-only stream for the contents of the resource specified by
1179 * {@code resName}. The mapping between the resource name and the stream is
1180 * managed by the class' class loader.
1183 * the name of the resource.
1184 * @return a stream for the requested resource or {@code null} if no
1185 * resource with the specified name can be found.
1188 public InputStream getResourceAsStream(String resName) {
1189 // Get absolute resource name, but without the leading slash
1190 if (resName.startsWith("/")) {
1191 resName = resName.substring(1);
1193 String pkg = getName();
1194 int dot = pkg.lastIndexOf('.');
1196 pkg = pkg.substring(0, dot).replace('.', '/');
1201 resName = pkg + "/" + resName;
1204 // Delegate to proper class loader
1205 ClassLoader loader = getClassLoader();
1206 if (loader != null) {
1207 return loader.getResourceAsStream(resName);
1209 return ClassLoader.getSystemResourceAsStream(resName);
1214 * Returns null. (On Android, a {@code ClassLoader} can load classes from multiple dex files.
1215 * All classes from any given dex file will have the same signers, but different dex
1216 * files may have different signers. This does not fit well with the original
1217 * {@code ClassLoader}-based model of {@code getSigners}.)
1221 public Object[] getSigners() {
1222 // See http://code.google.com/p/android/issues/detail?id=1766.
1227 * Returns the {@code Class} object which represents the superclass of the
1228 * class represented by this {@code Class}. If this {@code Class} represents
1229 * the {@code Object} class, a primitive type, an interface or void then the
1230 * method returns {@code null}. If this {@code Class} represents an array
1231 * class then the {@code Object} class is returned.
1233 * @return the superclass of the class represented by this {@code Class}.
1235 public native Class<? super T> getSuperclass();
1238 * Returns an array containing {@code TypeVariable} objects for type
1239 * variables declared by the generic class represented by this {@code
1240 * Class}. Returns an empty array if the class is not generic.
1242 * @return an array with the type variables of the class represented by this
1245 @SuppressWarnings("unchecked")
1246 public synchronized TypeVariable<Class<T>>[] getTypeParameters() {
1247 GenericSignatureParser parser = new GenericSignatureParser(getClassLoader());
1248 parser.parseForClass(this, getSignatureAttribute());
1249 return parser.formalTypeParameters.clone();
1253 * Indicates whether this {@code Class} represents an annotation class.
1255 * @return {@code true} if this {@code Class} represents an annotation
1256 * class; {@code false} otherwise.
1258 public boolean isAnnotation() {
1259 final int ACC_ANNOTATION = 0x2000; // not public in reflect.Modifiers
1260 int mod = getModifiers(this, true);
1261 return (mod & ACC_ANNOTATION) != 0;
1265 * Indicates whether the specified annotation is present for the class
1266 * represented by this {@code Class}.
1268 * @param annotationClass
1269 * the annotation to look for.
1270 * @return {@code true} if the class represented by this {@code Class} is
1271 * annotated with {@code annotationClass}; {@code false} otherwise.
1273 public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {
1274 return getAnnotation(annotationClass) != null;
1278 * Indicates whether the class represented by this {@code Class} is
1279 * anonymously declared.
1281 * @return {@code true} if the class represented by this {@code Class} is
1282 * anonymous; {@code false} otherwise.
1284 native public boolean isAnonymousClass();
1287 * Indicates whether the class represented by this {@code Class} is an array
1290 * @return {@code true} if the class represented by this {@code Class} is an
1291 * array class; {@code false} otherwise.
1293 public boolean isArray() {
1294 return getComponentType() != null;
1298 * Indicates whether the specified class type can be converted to the class
1299 * represented by this {@code Class}. Conversion may be done via an identity
1300 * conversion or a widening reference conversion (if either the receiver or
1301 * the argument represent primitive types, only the identity conversion
1305 * the class to check.
1306 * @return {@code true} if {@code cls} can be converted to the class
1307 * represented by this {@code Class}; {@code false} otherwise.
1308 * @throws NullPointerException
1309 * if {@code cls} is {@code null}.
1311 public native boolean isAssignableFrom(Class<?> cls);
1314 * Indicates whether the class represented by this {@code Class} is an
1317 * @return {@code true} if the class represented by this {@code Class} is an
1318 * {@code enum}; {@code false} otherwise.
1320 public boolean isEnum() {
1321 return ((getModifiers() & 0x4000) != 0) && (getSuperclass() == Enum.class);
1325 * Indicates whether the specified object can be cast to the class
1326 * represented by this {@code Class}. This is the runtime version of the
1327 * {@code instanceof} operator.
1330 * the object to check.
1331 * @return {@code true} if {@code object} can be cast to the type
1332 * represented by this {@code Class}; {@code false} if {@code
1333 * object} is {@code null} or cannot be cast.
1335 public native boolean isInstance(Object object);
1338 * Indicates whether this {@code Class} represents an interface.
1340 * @return {@code true} if this {@code Class} represents an interface;
1341 * {@code false} otherwise.
1343 public native boolean isInterface();
1346 * Indicates whether the class represented by this {@code Class} is defined
1349 * @return {@code true} if the class represented by this {@code Class} is
1350 * defined locally; {@code false} otherwise.
1352 public boolean isLocalClass() {
1353 boolean enclosed = (getEnclosingMethod() != null ||
1354 getEnclosingConstructor() != null);
1355 return enclosed && !isAnonymousClass();
1359 * Indicates whether the class represented by this {@code Class} is a member
1362 * @return {@code true} if the class represented by this {@code Class} is a
1363 * member class; {@code false} otherwise.
1365 public boolean isMemberClass() {
1366 return getDeclaringClass() != null;
1370 * Indicates whether this {@code Class} represents a primitive type.
1372 * @return {@code true} if this {@code Class} represents a primitive type;
1373 * {@code false} otherwise.
1375 public native boolean isPrimitive();
1378 * Indicates whether this {@code Class} represents a synthetic type.
1380 * @return {@code true} if this {@code Class} represents a synthetic type;
1381 * {@code false} otherwise.
1383 public boolean isSynthetic() {
1384 final int ACC_SYNTHETIC = 0x1000; // not public in reflect.Modifiers
1385 int mod = getModifiers(this, true);
1386 return (mod & ACC_SYNTHETIC) != 0;
1390 * Returns a new instance of the class represented by this {@code Class},
1391 * created by invoking the default (that is, zero-argument) constructor. If
1392 * there is no such constructor, or if the creation fails (either because of
1393 * a lack of available memory or because an exception is thrown by the
1394 * constructor), an {@code InstantiationException} is thrown. If the default
1395 * constructor exists but is not accessible from the context where this
1396 * method is invoked, an {@code IllegalAccessException} is thrown.
1398 * @return a new instance of the class represented by this {@code Class}.
1399 * @throws IllegalAccessException
1400 * if the default constructor is not visible.
1401 * @throws InstantiationException
1402 * if the instance can not be created.
1403 * @throws SecurityException
1404 * if a security manager exists and it does not allow creating
1407 public T newInstance() throws InstantiationException, IllegalAccessException {
1408 checkPublicMemberAccess();
1409 return newInstanceImpl();
1412 private native T newInstanceImpl() throws IllegalAccessException,
1413 InstantiationException;
1416 public String toString() {
1417 if (isPrimitive()) {
1418 return getSimpleName().toLowerCase();
1420 return (isInterface() ? "interface " : "class ") + getName();
1425 * Returns the {@code Package} of which the class represented by this
1426 * {@code Class} is a member. Returns {@code null} if no {@code Package}
1427 * object was created by the class loader of the class.
1429 * @return Package the {@code Package} of which this {@code Class} is a
1430 * member or {@code null}.
1432 public Package getPackage() {
1433 // TODO This might be a hack, but the VM doesn't have the necessary info.
1434 ClassLoader loader = getClassLoader();
1435 if (loader != null) {
1436 String name = getName();
1437 int dot = name.lastIndexOf('.');
1438 return (dot != -1 ? ClassLoader.getPackage(loader, name.substring(0, dot)) : null);
1445 * Returns the assertion status for the class represented by this {@code
1446 * Class}. Assertion is enabled / disabled based on the class loader,
1447 * package or class default at runtime.
1449 * @return the assertion status for the class represented by this {@code
1452 public native boolean desiredAssertionStatus();
1455 * Casts this {@code Class} to represent a subclass of the specified class.
1456 * If successful, this {@code Class} is returned; otherwise a {@code
1457 * ClassCastException} is thrown.
1460 * the required type.
1461 * @return this {@code Class} cast as a subclass of the given type.
1462 * @throws ClassCastException
1463 * if this {@code Class} cannot be cast to the specified type.
1465 @SuppressWarnings("unchecked")
1466 public <U> Class<? extends U> asSubclass(Class<U> clazz) {
1467 if (clazz.isAssignableFrom(this)) {
1468 return (Class<? extends U>)this;
1470 throw new ClassCastException();
1474 * Casts the specified object to the type represented by this {@code Class}.
1475 * If the object is {@code null} then the result is also {@code null}.
1478 * the object to cast.
1479 * @return the object that has been cast.
1480 * @throws ClassCastException
1481 * if the object cannot be cast to the specified type.
1483 @SuppressWarnings("unchecked")
1484 public T cast(Object obj) {
1487 } else if (this.isInstance(obj)) {
1490 throw new ClassCastException();
1494 * Set the "accessible" flag of the given object, without doing any
1497 * <p><b>Note:</b> This method is implemented in native code, and,
1498 * as such, is less efficient than using {@link ClassCache#REFLECT}
1499 * to achieve the same goal. This method exists solely to help
1500 * bootstrap the reflection bridge.</p>
1502 * @param ao non-null; the object to modify
1503 * @param flag the new value for the accessible flag
1505 /*package*/ static native void setAccessibleNoCheck(AccessibleObject ao,
1509 * Copies two arrays into one. Assumes that the destination array is large
1512 * @param result the destination array
1513 * @param head the first source array
1514 * @param tail the second source array
1515 * @return the destination array, that is, result
1517 private static <T extends Object> T[] arraycopy(T[] result, T[] head, T[] tail) {
1518 System.arraycopy(head, 0, result, 0, head.length);
1519 System.arraycopy(tail, 0, result, head.length, tail.length);
1524 * This must be provided by the vm vendor, as it is used by other provided
1525 * class implementations in this package. This method is used by
1526 * SecurityManager.classDepth(), and getClassContext() which use the
1527 * parameters (-1, false) and SecurityManager.classLoaderDepth(),
1528 * currentClassLoader(), and currentLoadedClass() which use the parameters
1529 * (-1, true). Walk the stack and answer an array containing the maxDepth
1530 * most recent classes on the stack of the calling thread. Starting with the
1531 * caller of the caller of getStackClasses(), return an array of not more
1532 * than maxDepth Classes representing the classes of running methods on the
1533 * stack (including native methods). Frames representing the VM
1534 * implementation of java.lang.reflect are not included in the list. If
1535 * stopAtPrivileged is true, the walk will terminate at any frame running
1536 * one of the following methods: <code><ul>
1537 * <li>java/security/AccessController.doPrivileged(Ljava/security/PrivilegedAction;)Ljava/lang/Object;</li>
1538 * <li>java/security/AccessController.doPrivileged(Ljava/security/PrivilegedExceptionAction;)Ljava/lang/Object;</li>
1539 * <li>java/security/AccessController.doPrivileged(Ljava/security/PrivilegedAction;Ljava/security/AccessControlContext;)Ljava/lang/Object;</li>
1540 * <li>java/security/AccessController.doPrivileged(Ljava/security/PrivilegedExceptionAction;Ljava/security/AccessControlContext;)Ljava/lang/Object;</li>
1541 * </ul></code> If one of the doPrivileged methods is found, the walk terminate
1542 * and that frame is NOT included in the returned array. Notes:
1544 * <li>This method operates on the defining classes of methods on stack.
1545 * NOT the classes of receivers.</li>
1546 * <li>The item at index zero in the result array describes the caller of
1547 * the caller of this method.</li>
1551 * maximum depth to walk the stack, -1 for the entire stack
1552 * @param stopAtPrivileged
1553 * stop at privileged classes
1554 * @return the array of the most recent classes on the stack
1556 static final Class<?>[] getStackClasses(int maxDepth, boolean stopAtPrivileged) {
1557 return VMStack.getClasses(maxDepth, stopAtPrivileged);