OSDN Git Service

original
[gb-231r1-is01/Gingerbread_2.3.3_r1_IS01.git] / libcore / luni / src / main / java / java / lang / Class.java
1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements.  See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License.  You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17 /*
18  * Copyright (C) 2006-2007 The Android Open Source Project
19  *
20  * Licensed under the Apache License, Version 2.0 (the "License");
21  * you may not use this file except in compliance with the License.
22  * You may obtain a copy of the License at
23  *
24  *      http://www.apache.org/licenses/LICENSE-2.0
25  *
26  * Unless required by applicable law or agreed to in writing, software
27  * distributed under the License is distributed on an "AS IS" BASIS,
28  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
29  * See the License for the specific language governing permissions and
30  * limitations under the License.
31  */
32
33 package java.lang;
34
35 import 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;
52 import java.net.URL;
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;
59
60 /**
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.
66  *
67  * <h4>Class instances representing object types (classes or interfaces)</h4>
68  * <p>
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).
76  * </p>
77  * <h4>Classes representing primitive types</h4>
78  * <p>
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:
85  * </p>
86  * <ul>
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>
96  * </ul>
97  * <p>
98  * <h4>Classes representing array classes</h4>
99  * <p>
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:
108  * </p>
109  * <ul>
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>
113  * </ul>
114  */
115 public final class Class<T> implements Serializable, AnnotatedElement, GenericDeclaration, Type {
116
117     private static final long serialVersionUID = 3206093459760846163L;
118
119     /**
120      * This field is initialized by dalvikvm when the class is loaded.
121      */
122     private transient ProtectionDomain pd;
123
124     /**
125      * null-ok; cache of reflective information, wrapped in a soft
126      * reference
127      */
128     private transient volatile SoftReference<ClassCache<T>> cacheRef;
129
130     /**
131      * Lazily computed name of this class; always prefer calling getName().
132      */
133     private transient String name;
134
135     private Class() {
136         // Prevent this class to be instantiated, instance
137         // should be created by JVM only
138     }
139
140     /**
141      * Get the Signature attribute for this class.  Returns null if not found.
142      */
143     private String getSignatureAttribute() {
144         Object[] annotation = getSignatureAnnotation();
145
146         if (annotation == null) {
147             return null;
148         }
149
150         return StringUtils.combineStrings(annotation);
151     }
152
153     /**
154      * Get the Signature annotation for this class.  Returns null if not found.
155      */
156     native private Object[] getSignatureAnnotation();
157
158     /**
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.
163      * <p>
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.
168      *
169      * @param className
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
178      *             class.
179      */
180     public static Class<?> forName(String className) throws ClassNotFoundException {
181         return forName(className, true, VMStack.getCallingClassLoader());
182     }
183
184     /**
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
189      * be obeyed.
190      * <p>
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
195      * executed.
196      *
197      * @param className
198      *            the name of the non-primitive-type class to find.
199      * @param initializeBoolean
200      *            indicates whether the class should be initialized.
201      * @param classLoader
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
210      *             class.
211      */
212     public static Class<?> forName(String className, boolean initializeBoolean,
213             ClassLoader classLoader) throws ClassNotFoundException {
214
215         if (classLoader == null) {
216             SecurityManager smgr = System.getSecurityManager();
217             if (smgr != null) {
218                 ClassLoader calling = VMStack.getCallingClassLoader();
219                 if (calling != null) {
220                     smgr.checkPermission(new RuntimePermission("getClassLoader"));
221                 }
222             }
223
224             classLoader = ClassLoader.getSystemClassLoader();
225         }
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.
232         Class<?> result;
233         try {
234             result = classForName(className, initializeBoolean,
235                     classLoader);
236         } catch (ClassNotFoundException e) {
237             Throwable cause = e.getCause();
238             if (cause instanceof ExceptionInInitializerError) {
239                 throw (ExceptionInInitializerError) cause;
240             }
241             throw e;
242         }
243         return result;
244     }
245
246     /*
247      * Returns a class by name without any security checks.
248      *
249      * @param className The name of the non-primitive type class to find
250      * @param initializeBoolean A boolean indicating whether the class should be
251      *        initialized
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
255      */
256     static native Class<?> classForName(String className, boolean initializeBoolean,
257             ClassLoader classLoader) throws ClassNotFoundException;
258
259     /**
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.
265      *
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
269      *             access.
270      */
271     public Class<?>[] getClasses() {
272         checkPublicMemberAccess();
273         return getFullListOfClasses(true);
274     }
275
276     /**
277      * Returns the annotation of the given type. If there is no such annotation
278      * then the method returns {@code null}.
279      *
280      * @param annotationClass
281      *            the annotation type.
282      * @return the annotation of the given type, or {@code null} if there is no
283      *         such annotation.
284      */
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])) {
290                 return (A)list[i];
291             }
292         }
293
294         return null;
295     }
296
297     /**
298      * Returns all the annotations of this class. If there are no annotations
299      * then an empty array is returned.
300      *
301      * @return a copy of the array containing this class' annotations.
302      * @see #getDeclaredAnnotations()
303      */
304     public Annotation[] getAnnotations() {
305         /*
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.
310          *
311          * It's possible to have duplicates when annotations are inherited.
312          * We use a Map to filter those out.
313          *
314          * HashMap might be overkill here.
315          */
316         HashMap<Class, Annotation> map = new HashMap<Class, Annotation>();
317         Annotation[] annos = getDeclaredAnnotations();
318
319         for (int i = annos.length-1; i >= 0; --i)
320             map.put(annos[i].annotationType(), annos[i]);
321
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]);
330                 }
331             }
332         }
333
334         /* convert annotation values from HashMap to array */
335         Collection<Annotation> coll = map.values();
336         return coll.toArray(new Annotation[coll.size()]);
337     }
338
339     /**
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}.
343      *
344      * @return this class' canonical name, or {@code null} if it does not have a
345      *         canonical name.
346      */
347     public String getCanonicalName() {
348         if (isLocalClass() || isAnonymousClass())
349             return null;
350
351         if (isArray()) {
352             /*
353              * The canonical name of an array type depends on the (existence of)
354              * the component type's canonical name.
355              */
356             String name = getComponentType().getCanonicalName();
357             if (name != null) {
358                 return name + "[]";
359             }
360         } else if (isMemberClass()) {
361             /*
362              * The canonical name of an inner class depends on the (existence
363              * of) the declaring class' canonical name.
364              */
365             String name = getDeclaringClass().getCanonicalName();
366             if (name != null) {
367                 return name + "." + getSimpleName();
368             }
369         } else {
370             /*
371              * The canonical name of a top-level class or primitive type is
372              * equal to the fully qualified name.
373              */
374             return getName();
375         }
376
377         /*
378          * Other classes don't have a canonical name.
379          */
380         return null;
381     }
382
383     /**
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.
389      *
390      * @return the class loader for the represented class.
391      * @throws SecurityException
392      *             if a security manager exists and it does not allow accessing
393      *             the class loader.
394      * @see ClassLoader
395      */
396     public ClassLoader getClassLoader() {
397         SecurityManager smgr = System.getSecurityManager();
398         ClassLoader loader = getClassLoaderImpl();
399         if (smgr != null && loader != null) {
400             ClassLoader calling = VMStack.getCallingClassLoader();
401
402             if (calling != null && !calling.isAncestorOf(loader)) {
403                 smgr.checkPermission(new RuntimePermission("getClassLoader"));
404             }
405         }
406
407         if (this.isPrimitive()) {
408             return null;
409         }
410
411         if (loader == null) {
412             loader = BootClassLoader.getInstance();
413         }
414
415         return loader;
416     }
417
418     /**
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.
426      *
427      * @return the ClassLoader
428      * @see ClassLoader#isSystemClassLoader()
429      */
430     ClassLoader getClassLoaderImpl() {
431         ClassLoader loader = getClassLoader(this);
432         return loader == null ? BootClassLoader.getInstance() : loader;
433     }
434
435     /*
436      * Returns the defining class loader for the given class.
437      *
438      * @param clazz the class the class loader of which we want
439      * @return the class loader
440      */
441     private static native ClassLoader getClassLoader(Class<?> clazz);
442
443     /**
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.
448      *
449      * @return the component type of this class.
450      */
451     public native Class<?> getComponentType();
452
453     /**
454      * Returns a {@code Constructor} object which represents the public
455      * constructor matching the specified parameter types.
456      *
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
465      *             access.
466      * @see #getDeclaredConstructor(Class[])
467      */
468     @SuppressWarnings("unchecked")
469     public Constructor<T> getConstructor(Class<?>... parameterTypes) throws NoSuchMethodException,
470             SecurityException {
471         checkPublicMemberAccess();
472         return getMatchingConstructor(getDeclaredConstructors(this, true), parameterTypes);
473     }
474
475     /**
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.
480      *
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
485      *             access.
486      * @see #getDeclaredConstructors()
487      */
488     public Constructor<?>[] getConstructors() throws SecurityException {
489         checkPublicMemberAccess();
490         return getDeclaredConstructors(this, true);
491     }
492
493     /**
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
497      * array is returned.
498      *
499      * @return a copy of the array containing the annotations defined for the
500      *         class that this {@code Class} represents.
501      * @see #getAnnotations()
502      */
503     native public Annotation[] getDeclaredAnnotations();
504
505     /**
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.
511      *
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
516      *             access.
517      */
518     public Class<?>[] getDeclaredClasses() throws SecurityException {
519         checkDeclaredMemberAccess();
520         return getDeclaredClasses(this, false);
521     }
522
523     /*
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.
527      *
528      * @param publicOnly reflects whether we want only public members or all of them
529      * @return the list of classes
530      */
531     private Class<?>[] getFullListOfClasses(boolean publicOnly) {
532         Class<?>[] result = getDeclaredClasses(this, publicOnly);
533
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);
540             }
541
542             clazz = clazz.getSuperclass();
543         }
544
545         return result;
546     }
547
548     /*
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.
551      *
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
555      */
556     native private static Class<?>[] getDeclaredClasses(Class<?> clazz,
557         boolean publicOnly);
558
559     /**
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}.
563      *
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
572      *             access.
573      * @see #getConstructor(Class[])
574      */
575     @SuppressWarnings("unchecked")
576     public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
577             throws NoSuchMethodException, SecurityException {
578         checkDeclaredMemberAccess();
579         return getMatchingConstructor(getDeclaredConstructors(this, false), parameterTypes);
580     }
581
582     /**
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.
587      *
588      * @return an array with the constructors declared in the class represented
589      *         by this {@code Class}.
590      *
591      * @throws SecurityException
592      *             if a security manager exists and it does not allow member
593      *             access.
594      * @see #getConstructors()
595      */
596     public Constructor<?>[] getDeclaredConstructors() throws SecurityException {
597         checkDeclaredMemberAccess();
598         return getDeclaredConstructors(this, false);
599     }
600
601     /*
602      * Returns the list of constructors without performing any security checks
603      * first. If no constructors exist, an empty array is returned.
604      *
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
608      */
609     private static native <T> Constructor<T>[] getDeclaredConstructors(Class<T> clazz, boolean publicOnly);
610
611     /*
612      * Finds a constructor with a given signature.
613      *
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.
618      */
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)) {
624                 return list[i];
625             }
626         }
627
628         // BEGIN android-changed
629         StringBuilder sb = new StringBuilder();
630         sb.append(getSimpleName());
631         sb.append('(');
632         boolean first = true;
633         if (parameterTypes != null) {
634             for (Class<?> p : parameterTypes) {
635                 if (!first) {
636                     sb.append(',');
637                 }
638                 first = false;
639                 sb.append(p.getSimpleName());
640             }
641         }
642         sb.append(')');
643         throw new NoSuchMethodException(sb.toString());
644         // END android-changed
645     }
646
647     /**
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}.
650      *
651      * @param name
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
658      *             access.
659      * @see #getField(String)
660      */
661     public Field getDeclaredField(String name)
662             throws NoSuchFieldException, SecurityException {
663         checkDeclaredMemberAccess();
664
665         Field[] fields = getClassCache().getDeclaredFields();
666         Field field = findFieldByName(fields, name);
667
668         /*
669          * Make a copy of the private (to the package) object, so that
670          * setAccessible() won't alter the private instance.
671          */
672         return REFLECT.clone(field);
673     }
674
675     /**
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.
680      *
681      * @return an array with the fields declared in the class represented by
682      *         this class.
683      * @throws SecurityException
684      *             if a security manager exists and it does not allow member
685      *             access.
686      * @see #getFields()
687      */
688     public Field[] getDeclaredFields() throws SecurityException {
689         checkDeclaredMemberAccess();
690
691         // Return a copy of the private (to the package) array.
692         Field[] fields = getClassCache().getDeclaredFields();
693         return ClassCache.deepCopy(fields);
694     }
695
696     /*
697      * Returns the list of fields without performing any security checks
698      * first. If no fields exist at all, an empty array is returned.
699      *
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
703      */
704     static native Field[] getDeclaredFields(Class<?> clazz, boolean publicOnly);
705
706     /**
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}.
710      *
711      * @param name
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
723      *             access.
724      * @see #getMethod(String, Class[])
725      */
726     public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
727             throws NoSuchMethodException, SecurityException {
728         checkDeclaredMemberAccess();
729
730         Method[] methods = getClassCache().getDeclaredMethods();
731         Method method = findMethodByName(methods, name, parameterTypes);
732
733         /*
734          * Make a copy of the private (to the package) object, so that
735          * setAccessible() won't alter the private instance.
736          */
737         return REFLECT.clone(method);
738     }
739
740     /**
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.
745      *
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
750      *             access.
751      * @see #getMethods()
752      */
753     public Method[] getDeclaredMethods() throws SecurityException {
754         checkDeclaredMemberAccess();
755
756         // Return a copy of the private (to the package) array.
757         Method[] methods = getClassCache().getDeclaredMethods();
758         return ClassCache.deepCopy(methods);
759     }
760
761     /**
762      * Returns the list of methods without performing any security checks
763      * first. If no methods exist, an empty array is returned.
764      */
765     static native Method[] getDeclaredMethods(Class<?> clazz, boolean publicOnly);
766
767     /**
768      * Gets the {@link ClassCache} for this instance.
769      *
770      * @return non-null; the cache object
771      */
772     /*package*/ ClassCache<T> getClassCache() {
773         /*
774          * Note: It is innocuous if two threads try to simultaneously
775          * create the cache, so we don't bother protecting against that.
776          */
777         ClassCache<T> cache = null;
778
779         if (cacheRef != null) {
780             cache = cacheRef.get();
781         }
782
783         if (cache == null) {
784             cache = new ClassCache<T>(this);
785             cacheRef = new SoftReference<ClassCache<T>>(cache);
786         }
787
788         return cache;
789     }
790
791     /**
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.
795      *
796      * @return the declaring {@code Class} or {@code null}.
797      */
798     native public Class<?> getDeclaringClass();
799
800     /**
801      * Returns the enclosing {@code Class} of this {@code Class}. If there is no
802      * enclosing class the method returns {@code null}.
803      *
804      * @return the enclosing {@code Class} or {@code null}.
805      */
806     native public Class<?> getEnclosingClass();
807
808     /**
809      * Gets the enclosing {@code Constructor} of this {@code Class}, if it is an
810      * anonymous or local/automatic class; otherwise {@code null}.
811      *
812      * @return the enclosing {@code Constructor} instance or {@code null}.
813      */
814     native public Constructor<?> getEnclosingConstructor();
815
816     /**
817      * Gets the enclosing {@code Method} of this {@code Class}, if it is an
818      * anonymous or local/automatic class; otherwise {@code null}.
819      *
820      * @return the enclosing {@code Method} instance or {@code null}.
821      */
822     native public Method getEnclosingMethod();
823
824     /**
825      * Gets the {@code enum} constants associated with this {@code Class}.
826      * Returns {@code null} if this {@code Class} does not represent an {@code
827      * enum} type.
828      *
829      * @return an array with the {@code enum} constants or {@code null}.
830      */
831     @SuppressWarnings("unchecked")
832     public T[] getEnumConstants() {
833         if (isEnum()) {
834             checkPublicMemberAccess();
835             T[] values = getClassCache().getEnumValuesInOrder();
836
837             // Copy the private (to the package) array.
838             return (T[]) values.clone();
839         }
840
841         return null;
842     }
843
844     /**
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
848      * superclasses of C.
849      *
850      * @param name
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
857      *             access.
858      * @see #getDeclaredField(String)
859      */
860     public Field getField(String name) throws NoSuchFieldException, SecurityException {
861         checkPublicMemberAccess();
862
863         Field[] fields = getClassCache().getAllPublicFields();
864         Field field = findFieldByName(fields, name);
865
866         /*
867          * Make a copy of the private (to the package) object, so that
868          * setAccessible() won't alter the private instance.
869          */
870         return REFLECT.clone(field);
871     }
872
873     /**
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.
878      * <p>
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.
881      * </p>
882      *
883      * @return an array with the public fields of the class represented by this
884      *         {@code Class}.
885      * @throws SecurityException
886      *             if a security manager exists and it does not allow member
887      *             access.
888      * @see #getDeclaredFields()
889      */
890     public Field[] getFields() throws SecurityException {
891         checkPublicMemberAccess();
892
893         // Return a copy of the private (to the package) array.
894         Field[] fields = getClassCache().getAllPublicFields();
895         return ClassCache.deepCopy(fields);
896     }
897
898     /**
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.
902      *
903      * @return an array of {@link Type} instances directly implemented by the
904      *         class represented by this {@code class}.
905      */
906     public Type[] getGenericInterfaces() {
907         GenericSignatureParser parser = new GenericSignatureParser(getClassLoader());
908         parser.parseForClass(this, getSignatureAttribute());
909         return Types.getClonedTypeArray(parser.interfaceTypes);
910     }
911
912     /**
913      * Gets the {@code Type} that represents the superclass of this {@code
914      * class}.
915      *
916      * @return an instance of {@code Type} representing the superclass.
917      */
918     public Type getGenericSuperclass() {
919         GenericSignatureParser parser = new GenericSignatureParser(getClassLoader());
920         parser.parseForClass(this, getSignatureAttribute());
921         return Types.getType(parser.superclassType);
922     }
923
924     /**
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.
930      *
931      * @return an array with the interfaces of the class represented by this
932      *         class.
933      */
934     public native Class<?>[] getInterfaces();
935
936     // Changed to raw type to be closer to the RI
937     /**
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.
943      *
944      * @param 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
954      *             access.
955      * @see #getDeclaredMethod(String, Class[])
956      */
957     public Method getMethod(String name, Class<?>... parameterTypes) throws NoSuchMethodException,
958             SecurityException {
959         checkPublicMemberAccess();
960
961         Method[] methods = getClassCache().getMethods();
962         Method method = findMethodByName(methods, name, parameterTypes);
963
964         /*
965          * Make a copy of the private (to the package) object, so that
966          * setAccessible() won't alter the private instance.
967          */
968         return REFLECT.clone(method);
969     }
970
971     /**
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.
976      * <p>
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.
979      * </p>
980      *
981      * @return an array with the methods of the class represented by this
982      *         {@code Class}.
983      * @throws SecurityException
984      *             if a security manager exists and it does not allow member
985      *             access.
986      * @see #getDeclaredMethods()
987      */
988     public Method[] getMethods() throws SecurityException {
989         checkPublicMemberAccess();
990
991         // Return a copy of the private (to the package) array.
992         Method[] methods = getClassCache().getMethods();
993         return ClassCache.deepCopy(methods);
994     }
995
996     /**
997      * Performs the security checks regarding the access of a public
998      * member of this {@code Class}.
999      *
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>
1003      */
1004     /*package*/ void checkPublicMemberAccess() {
1005         SecurityManager smgr = System.getSecurityManager();
1006
1007         if (smgr != null) {
1008             smgr.checkMemberAccess(this, Member.PUBLIC);
1009
1010             ClassLoader calling = VMStack.getCallingClassLoader2();
1011             ClassLoader current = getClassLoader();
1012
1013             if (calling != null && !calling.isAncestorOf(current)) {
1014                 smgr.checkPackageAccess(this.getPackage().getName());
1015             }
1016         }
1017     }
1018
1019     /**
1020      * Performs the security checks regarding the access of a declared
1021      * member of this {@code Class}.
1022      *
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>
1026      */
1027     private void checkDeclaredMemberAccess() {
1028         SecurityManager smgr = System.getSecurityManager();
1029         if (smgr != null) {
1030             smgr.checkMemberAccess(this, Member.DECLARED);
1031
1032             ClassLoader calling = VMStack.getCallingClassLoader2();
1033             ClassLoader current = getClassLoader();
1034
1035             if (calling != null && !calling.isAncestorOf(current)) {
1036                 smgr.checkPackageAccess(this.getPackage().getName());
1037             }
1038         }
1039     }
1040
1041     /**
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.
1045      *
1046      * @return the modifiers of the class represented by this {@code Class}.
1047      */
1048     public int getModifiers() {
1049         return getModifiers(this, false);
1050     }
1051
1052     /*
1053      * Return the modifiers for the given class.
1054      *
1055      * @param clazz the class of interest
1056      * @ignoreInnerClassesAttrib determines whether we look for and use the
1057      *     flags from an "inner class" attribute
1058      */
1059     private static native int getModifiers(Class<?> clazz, boolean ignoreInnerClassesAttrib);
1060
1061     /**
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
1064      * {@link Class}.
1065      *
1066      * @return the name of the class represented by this {@code Class}.
1067      */
1068     public String getName() {
1069         String result = name;
1070         return (result == null) ? (name = getNameNative()) : result;
1071     }
1072
1073     private native String getNameNative();
1074
1075     /**
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 &quot;Integer[]&quot;}) is returned.
1081      *
1082      * @return the simple name of the class represented by this {@code Class}.
1083      */
1084     public String getSimpleName() {
1085         if (isArray()) {
1086             return getComponentType().getSimpleName() + "[]";
1087         }
1088
1089         String name = getName();
1090
1091         if (isAnonymousClass()) {
1092             return "";
1093         }
1094
1095         if (isMemberClass() || isLocalClass()) {
1096             return getInnerClassName();
1097         }
1098
1099         int dot = name.lastIndexOf('.');
1100         if (dot != -1) {
1101             return name.substring(dot + 1);
1102         }
1103
1104         return name;
1105     }
1106
1107     /*
1108      * Returns the simple name of a member or local class, or null otherwise.
1109      *
1110      * @return The name.
1111      */
1112     private native String getInnerClassName();
1113
1114     /**
1115      * Returns the {@code ProtectionDomain} of the class represented by this
1116      * class.
1117      * <p>
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.
1123      * </p>
1124      *
1125      * @return the {@code ProtectionDomain} of the class represented by this
1126      *         class.
1127      * @throws SecurityException
1128      *             if a security manager exists and it does not allow member
1129      *             access.
1130      */
1131     public ProtectionDomain getProtectionDomain() {
1132         SecurityManager smgr = System.getSecurityManager();
1133         if (smgr != null) {
1134             // Security check is independent of calling class loader.
1135             smgr.checkPermission(new RuntimePermission("getProtectionDomain"));
1136         }
1137
1138         return pd;
1139     }
1140
1141     /**
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
1144      * loader.
1145      *
1146      * @param resName
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.
1150      * @see ClassLoader
1151      */
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);
1156         } else {
1157             String pkg = getName();
1158             int dot = pkg.lastIndexOf('.');
1159             if (dot != -1) {
1160                 pkg = pkg.substring(0, dot).replace('.', '/');
1161             } else {
1162                 pkg = "";
1163             }
1164
1165             resName = pkg + "/" + resName;
1166         }
1167
1168         // Delegate to proper class loader
1169         ClassLoader loader = getClassLoader();
1170         if (loader != null) {
1171             return loader.getResource(resName);
1172         } else {
1173             return ClassLoader.getSystemResource(resName);
1174         }
1175     }
1176
1177     /**
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.
1181      *
1182      * @param resName
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.
1186      * @see ClassLoader
1187      */
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);
1192         } else {
1193             String pkg = getName();
1194             int dot = pkg.lastIndexOf('.');
1195             if (dot != -1) {
1196                 pkg = pkg.substring(0, dot).replace('.', '/');
1197             } else {
1198                 pkg = "";
1199             }
1200
1201             resName = pkg + "/" + resName;
1202         }
1203
1204         // Delegate to proper class loader
1205         ClassLoader loader = getClassLoader();
1206         if (loader != null) {
1207             return loader.getResourceAsStream(resName);
1208         } else {
1209             return ClassLoader.getSystemResourceAsStream(resName);
1210         }
1211     }
1212
1213     /**
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}.)
1218      *
1219      * @return null.
1220      */
1221     public Object[] getSigners() {
1222         // See http://code.google.com/p/android/issues/detail?id=1766.
1223         return null;
1224     }
1225
1226     /**
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.
1232      *
1233      * @return the superclass of the class represented by this {@code Class}.
1234      */
1235     public native Class<? super T> getSuperclass();
1236
1237     /**
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.
1241      *
1242      * @return an array with the type variables of the class represented by this
1243      *         class.
1244      */
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();
1250     }
1251
1252     /**
1253      * Indicates whether this {@code Class} represents an annotation class.
1254      *
1255      * @return {@code true} if this {@code Class} represents an annotation
1256      *         class; {@code false} otherwise.
1257      */
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;
1262     }
1263
1264     /**
1265      * Indicates whether the specified annotation is present for the class
1266      * represented by this {@code Class}.
1267      *
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.
1272      */
1273     public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {
1274         return getAnnotation(annotationClass) != null;
1275     }
1276
1277     /**
1278      * Indicates whether the class represented by this {@code Class} is
1279      * anonymously declared.
1280      *
1281      * @return {@code true} if the class represented by this {@code Class} is
1282      *         anonymous; {@code false} otherwise.
1283      */
1284     native public boolean isAnonymousClass();
1285
1286     /**
1287      * Indicates whether the class represented by this {@code Class} is an array
1288      * class.
1289      *
1290      * @return {@code true} if the class represented by this {@code Class} is an
1291      *         array class; {@code false} otherwise.
1292      */
1293     public boolean isArray() {
1294         return getComponentType() != null;
1295     }
1296
1297     /**
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
1302      * applies).
1303      *
1304      * @param cls
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}.
1310      */
1311     public native boolean isAssignableFrom(Class<?> cls);
1312
1313     /**
1314      * Indicates whether the class represented by this {@code Class} is an
1315      * {@code enum}.
1316      *
1317      * @return {@code true} if the class represented by this {@code Class} is an
1318      *         {@code enum}; {@code false} otherwise.
1319      */
1320     public boolean isEnum() {
1321         return ((getModifiers() & 0x4000) != 0) && (getSuperclass() == Enum.class);
1322     }
1323
1324     /**
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.
1328      *
1329      * @param object
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.
1334      */
1335     public native boolean isInstance(Object object);
1336
1337     /**
1338      * Indicates whether this {@code Class} represents an interface.
1339      *
1340      * @return {@code true} if this {@code Class} represents an interface;
1341      *         {@code false} otherwise.
1342      */
1343     public native boolean isInterface();
1344
1345     /**
1346      * Indicates whether the class represented by this {@code Class} is defined
1347      * locally.
1348      *
1349      * @return {@code true} if the class represented by this {@code Class} is
1350      *         defined locally; {@code false} otherwise.
1351      */
1352     public boolean isLocalClass() {
1353         boolean enclosed = (getEnclosingMethod() != null ||
1354                          getEnclosingConstructor() != null);
1355         return enclosed && !isAnonymousClass();
1356     }
1357
1358     /**
1359      * Indicates whether the class represented by this {@code Class} is a member
1360      * class.
1361      *
1362      * @return {@code true} if the class represented by this {@code Class} is a
1363      *         member class; {@code false} otherwise.
1364      */
1365     public boolean isMemberClass() {
1366         return getDeclaringClass() != null;
1367     }
1368
1369     /**
1370      * Indicates whether this {@code Class} represents a primitive type.
1371      *
1372      * @return {@code true} if this {@code Class} represents a primitive type;
1373      *         {@code false} otherwise.
1374      */
1375     public native boolean isPrimitive();
1376
1377     /**
1378      * Indicates whether this {@code Class} represents a synthetic type.
1379      *
1380      * @return {@code true} if this {@code Class} represents a synthetic type;
1381      *         {@code false} otherwise.
1382      */
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;
1387     }
1388
1389     /**
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.
1397      *
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
1405      *             new instances.
1406      */
1407     public T newInstance() throws InstantiationException, IllegalAccessException {
1408         checkPublicMemberAccess();
1409         return newInstanceImpl();
1410     }
1411
1412     private native T newInstanceImpl() throws IllegalAccessException,
1413             InstantiationException;
1414
1415     @Override
1416     public String toString() {
1417         if (isPrimitive()) {
1418             return getSimpleName().toLowerCase();
1419         } else {
1420             return (isInterface() ? "interface " : "class ") + getName();
1421         }
1422     }
1423
1424     /**
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.
1428      *
1429      * @return Package the {@code Package} of which this {@code Class} is a
1430      *         member or {@code null}.
1431      */
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);
1439         }
1440
1441         return null;
1442     }
1443
1444     /**
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.
1448      *
1449      * @return the assertion status for the class represented by this {@code
1450      *         Class}.
1451      */
1452     public native boolean desiredAssertionStatus();
1453
1454     /**
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.
1458      *
1459      * @param clazz
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.
1464      */
1465     @SuppressWarnings("unchecked")
1466     public <U> Class<? extends U> asSubclass(Class<U> clazz) {
1467         if (clazz.isAssignableFrom(this)) {
1468             return (Class<? extends U>)this;
1469         }
1470         throw new ClassCastException();
1471     }
1472
1473     /**
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}.
1476      *
1477      * @param obj
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.
1482      */
1483     @SuppressWarnings("unchecked")
1484     public T cast(Object obj) {
1485         if (obj == null) {
1486             return null;
1487         } else if (this.isInstance(obj)) {
1488             return (T)obj;
1489         }
1490         throw new ClassCastException();
1491     }
1492
1493     /**
1494      * Set the "accessible" flag of the given object, without doing any
1495      * access checks.
1496      *
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>
1501      *
1502      * @param ao non-null; the object to modify
1503      * @param flag the new value for the accessible flag
1504      */
1505     /*package*/ static native void setAccessibleNoCheck(AccessibleObject ao,
1506             boolean flag);
1507
1508     /**
1509      * Copies two arrays into one. Assumes that the destination array is large
1510      * enough.
1511      *
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
1516      */
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);
1520         return result;
1521     }
1522
1523     /**
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:
1543      * <ul>
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>
1548      * </ul>
1549      *
1550      * @param maxDepth
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
1555      */
1556     static final Class<?>[] getStackClasses(int maxDepth, boolean stopAtPrivileged) {
1557         return VMStack.getClasses(maxDepth, stopAtPrivileged);
1558     }
1559
1560 }