OSDN Git Service

Merged gcj-eclipse branch to trunk.
[pf3gnuchains/gcc-fork.git] / libjava / classpath / java / lang / Class.java
1 /* Class.java -- Representation of a Java class.
2    Copyright (C) 1998, 1999, 2000, 2002, 2003, 2004, 2005, 2006
3    Free Software Foundation
4
5 This file is part of GNU Classpath.
6
7 GNU Classpath is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
11
12 GNU Classpath is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GNU Classpath; see the file COPYING.  If not, write to the
19 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
20 02110-1301 USA.
21
22 Linking this library statically or dynamically with other modules is
23 making a combined work based on this library.  Thus, the terms and
24 conditions of the GNU General Public License cover the whole
25 combination.
26
27 As a special exception, the copyright holders of this library give you
28 permission to link this library with independent modules to produce an
29 executable, regardless of the license terms of these independent
30 modules, and to copy and distribute the resulting executable under
31 terms of your choice, provided that you also meet, for each linked
32 independent module, the terms and conditions of the license of that
33 module.  An independent module is a module which is not derived from
34 or based on this library.  If you modify this library, you may extend
35 this exception to your version of the library, but you are not
36 obligated to do so.  If you do not wish to do so, delete this
37 exception statement from your version. */
38
39 package java.lang;
40
41 import gnu.classpath.VMStackWalker;
42 import gnu.java.lang.reflect.ClassSignatureParser;
43
44 import java.io.InputStream;
45 import java.io.Serializable;
46 import java.lang.annotation.Annotation;
47 import java.lang.annotation.Inherited;
48 import java.lang.reflect.AnnotatedElement;
49 import java.lang.reflect.Constructor;
50 import java.lang.reflect.Field;
51 import java.lang.reflect.GenericDeclaration;
52 import java.lang.reflect.InvocationTargetException;
53 import java.lang.reflect.Member;
54 import java.lang.reflect.Method;
55 import java.lang.reflect.Modifier;
56 import java.lang.reflect.Type;
57 import java.lang.reflect.TypeVariable;
58 import java.net.URL;
59 import java.security.AccessController;
60 import java.security.AllPermission;
61 import java.security.Permissions;
62 import java.security.PrivilegedAction;
63 import java.security.ProtectionDomain;
64 import java.util.ArrayList;
65 import java.util.Arrays;
66 import java.util.Collection;
67 import java.util.HashMap;
68 import java.util.HashSet;
69
70
71 /**
72  * A Class represents a Java type.  There will never be multiple Class
73  * objects with identical names and ClassLoaders. Primitive types, array
74  * types, and void also have a Class object.
75  *
76  * <p>Arrays with identical type and number of dimensions share the same class.
77  * The array class ClassLoader is the same as the ClassLoader of the element
78  * type of the array (which can be null to indicate the bootstrap classloader).
79  * The name of an array class is <code>[&lt;signature format&gt;;</code>.
80  * <p> For example,
81  * String[]'s class is <code>[Ljava.lang.String;</code>. boolean, byte,
82  * short, char, int, long, float and double have the "type name" of
83  * Z,B,S,C,I,J,F,D for the purposes of array classes.  If it's a
84  * multidimensioned array, the same principle applies:
85  * <code>int[][][]</code> == <code>[[[I</code>.
86  *
87  * <p>There is no public constructor - Class objects are obtained only through
88  * the virtual machine, as defined in ClassLoaders.
89  *
90  * @serialData Class objects serialize specially:
91  * <code>TC_CLASS ClassDescriptor</code>. For more serialization information,
92  * see {@link ObjectStreamClass}.
93  *
94  * @author John Keiser
95  * @author Eric Blake (ebb9@email.byu.edu)
96  * @author Tom Tromey (tromey@redhat.com)
97  * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
98  * @since 1.0
99  * @see ClassLoader
100  */
101 public final class Class<T> 
102   implements Serializable, Type, AnnotatedElement, GenericDeclaration
103 {
104   /**
105    * Compatible with JDK 1.0+.
106    */
107   private static final long serialVersionUID = 3206093459760846163L;
108
109   /**
110    * Flag indicating a synthetic member.
111    * Note that this duplicates a constant in Modifier.
112    */
113   private static final int SYNTHETIC = 0x1000;
114
115   /**
116    * Flag indiciating an annotation class.
117    */
118   private static final int ANNOTATION = 0x2000;
119
120   /**
121    * Flag indicating an enum constant or an enum class.
122    * Note that this duplicates a constant in Modifier.
123    */
124   private static final int ENUM = 0x4000;
125
126   /** The class signers. */
127   private Object[] signers = null;
128   /** The class protection domain. */
129   private final transient ProtectionDomain pd;
130
131   /* We use an inner class, so that Class doesn't have a static initializer */
132   private static final class StaticData
133   {
134     static final ProtectionDomain unknownProtectionDomain;
135
136     static
137     {
138       Permissions permissions = new Permissions();
139       permissions.add(new AllPermission());
140       unknownProtectionDomain = new ProtectionDomain(null, permissions);
141     }
142   }
143
144   final transient Object vmdata;
145
146   /** newInstance() caches the default constructor */
147   private transient Constructor<T> constructor;
148
149   /**
150    * Class is non-instantiable from Java code; only the VM can create
151    * instances of this class.
152    */
153   Class(Object vmdata)
154   {
155     this(vmdata, null);
156   }
157
158   Class(Object vmdata, ProtectionDomain pd)
159   {
160     this.vmdata = vmdata;
161     // If the VM didn't supply a protection domain and the class is an array,
162     // we "inherit" the protection domain from the component type class. This
163     // saves the VM from having to worry about protection domains for array
164     // classes.
165     if (pd == null && isArray())
166       this.pd = getComponentType().pd;
167     else
168       this.pd = pd;
169   }
170
171   /**
172    * Use the classloader of the current class to load, link, and initialize
173    * a class. This is equivalent to your code calling
174    * <code>Class.forName(name, true, getClass().getClassLoader())</code>.
175    *
176    * @param name the name of the class to find
177    * @return the Class object representing the class
178    * @throws ClassNotFoundException if the class was not found by the
179    *         classloader
180    * @throws LinkageError if linking the class fails
181    * @throws ExceptionInInitializerError if the class loads, but an exception
182    *         occurs during initialization
183    */
184   public static Class<?> forName(String name) throws ClassNotFoundException
185   {
186     return VMClass.forName(name, true, VMStackWalker.getCallingClassLoader());
187   }
188
189   /**
190    * Use the specified classloader to load and link a class. If the loader
191    * is null, this uses the bootstrap class loader (provide the security
192    * check succeeds). Unfortunately, this method cannot be used to obtain
193    * the Class objects for primitive types or for void, you have to use
194    * the fields in the appropriate java.lang wrapper classes.
195    *
196    * <p>Calls <code>classloader.loadclass(name, initialize)</code>.
197    *
198    * @param name the name of the class to find
199    * @param initialize whether or not to initialize the class at this time
200    * @param classloader the classloader to use to find the class; null means
201    *        to use the bootstrap class loader
202    *
203    * @return the class object for the given class
204    *
205    * @throws ClassNotFoundException if the class was not found by the
206    *         classloader
207    * @throws LinkageError if linking the class fails
208    * @throws ExceptionInInitializerError if the class loads, but an exception
209    *         occurs during initialization
210    * @throws SecurityException if the <code>classloader</code> argument
211    *         is <code>null</code> and the caller does not have the
212    *         <code>RuntimePermission("getClassLoader")</code> permission
213    * @see ClassLoader
214    * @since 1.2
215    */
216   public static Class<?> forName(String name, boolean initialize,
217                                  ClassLoader classloader)
218     throws ClassNotFoundException
219   {
220     if (classloader == null)
221       {
222         // Check if we may access the bootstrap classloader
223         SecurityManager sm = SecurityManager.current;
224         if (sm != null)
225           {
226             // Get the calling classloader
227             ClassLoader cl = VMStackWalker.getCallingClassLoader();
228             if (cl != null)
229               sm.checkPermission(new RuntimePermission("getClassLoader"));
230           }
231       }
232     return (Class<?>) VMClass.forName(name, initialize, classloader);
233   }
234   
235   /**
236    * Get all the public member classes and interfaces declared in this
237    * class or inherited from superclasses. This returns an array of length
238    * 0 if there are no member classes, including for primitive types. A
239    * security check may be performed, with
240    * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
241    * <code>checkPackageAccess</code> both having to succeed.
242    *
243    * @return all public member classes in this class
244    * @throws SecurityException if the security check fails
245    * @since 1.1
246    */
247   public Class<?>[] getClasses()
248   {
249     memberAccessCheck(Member.PUBLIC);
250     return internalGetClasses();
251   }
252
253   /**
254    * Like <code>getClasses()</code> but without the security checks.
255    */
256   private Class<?>[] internalGetClasses()
257   {
258     ArrayList<Class> list = new ArrayList<Class>();
259     list.addAll(Arrays.asList(getDeclaredClasses(true)));
260     Class superClass = getSuperclass();
261     if (superClass != null)
262       list.addAll(Arrays.asList(superClass.internalGetClasses()));
263     return list.toArray(new Class<?>[list.size()]);
264   }
265   
266   /**
267    * Get the ClassLoader that loaded this class.  If the class was loaded
268    * by the bootstrap classloader, this method will return null.
269    * If there is a security manager, and the caller's class loader is not
270    * an ancestor of the requested one, a security check of
271    * <code>RuntimePermission("getClassLoader")</code>
272    * must first succeed. Primitive types and void return null.
273    *
274    * @return the ClassLoader that loaded this class
275    * @throws SecurityException if the security check fails
276    * @see ClassLoader
277    * @see RuntimePermission
278    */
279   public ClassLoader getClassLoader()
280   {
281     if (isPrimitive())
282       return null;
283
284     ClassLoader loader = VMClass.getClassLoader(this);
285     // Check if we may get the classloader
286     SecurityManager sm = SecurityManager.current;
287     if (loader != null && sm != null)
288       {
289         // Get the calling classloader
290         ClassLoader cl = VMStackWalker.getCallingClassLoader();
291         if (cl != null && !cl.isAncestorOf(loader))
292           sm.checkPermission(new RuntimePermission("getClassLoader"));
293       }
294     return loader;
295   }
296
297   /**
298    * If this is an array, get the Class representing the type of array.
299    * Examples: "[[Ljava.lang.String;" would return "[Ljava.lang.String;", and
300    * calling getComponentType on that would give "java.lang.String".  If
301    * this is not an array, returns null.
302    *
303    * @return the array type of this class, or null
304    * @see Array
305    * @since 1.1
306    */
307   public Class<?> getComponentType()
308   {
309     return VMClass.getComponentType (this);
310   }
311
312   /**
313    * Get a public constructor declared in this class. If the constructor takes
314    * no argument, an array of zero elements and null are equivalent for the
315    * types argument. A security check may be performed, with
316    * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
317    * <code>checkPackageAccess</code> both having to succeed.
318    *
319    * @param types the type of each parameter
320    * @return the constructor
321    * @throws NoSuchMethodException if the constructor does not exist
322    * @throws SecurityException if the security check fails
323    * @see #getConstructors()
324    * @since 1.1
325    */
326   public Constructor<T> getConstructor(Class<?>... types)
327     throws NoSuchMethodException
328   {
329     memberAccessCheck(Member.PUBLIC);
330     Constructor[] constructors = getDeclaredConstructors(true);
331     for (int i = 0; i < constructors.length; i++)
332       {
333         Constructor constructor = constructors[i];
334         if (matchParameters(types, constructor.getParameterTypes()))
335           return constructor;
336       }
337     throw new NoSuchMethodException();
338   }
339
340   /**
341    * Get all the public constructors of this class. This returns an array of
342    * length 0 if there are no constructors, including for primitive types,
343    * arrays, and interfaces. It does, however, include the default
344    * constructor if one was supplied by the compiler. A security check may
345    * be performed, with <code>checkMemberAccess(this, Member.PUBLIC)</code>
346    * as well as <code>checkPackageAccess</code> both having to succeed.
347    *
348    * @return all public constructors in this class
349    * @throws SecurityException if the security check fails
350    * @since 1.1
351    */
352   public Constructor<?>[] getConstructors()
353   {
354     memberAccessCheck(Member.PUBLIC);
355     return getDeclaredConstructors(true);
356   }
357
358   /**
359    * Get a constructor declared in this class. If the constructor takes no
360    * argument, an array of zero elements and null are equivalent for the
361    * types argument. A security check may be performed, with
362    * <code>checkMemberAccess(this, Member.DECLARED)</code> as well as
363    * <code>checkPackageAccess</code> both having to succeed.
364    *
365    * @param types the type of each parameter
366    * @return the constructor
367    * @throws NoSuchMethodException if the constructor does not exist
368    * @throws SecurityException if the security check fails
369    * @see #getDeclaredConstructors()
370    * @since 1.1
371    */
372   public Constructor<T> getDeclaredConstructor(Class<?>... types)
373     throws NoSuchMethodException
374   {
375     memberAccessCheck(Member.DECLARED);
376     Constructor[] constructors = getDeclaredConstructors(false);
377     for (int i = 0; i < constructors.length; i++)
378       {
379         Constructor constructor = constructors[i];
380         if (matchParameters(types, constructor.getParameterTypes()))
381           return constructor;
382       }
383     throw new NoSuchMethodException();
384   }
385
386   /**
387    * Get all the declared member classes and interfaces in this class, but
388    * not those inherited from superclasses. This returns an array of length
389    * 0 if there are no member classes, including for primitive types. A
390    * security check may be performed, with
391    * <code>checkMemberAccess(this, Member.DECLARED)</code> as well as
392    * <code>checkPackageAccess</code> both having to succeed.
393    *
394    * @return all declared member classes in this class
395    * @throws SecurityException if the security check fails
396    * @since 1.1
397    */
398   public Class<?>[] getDeclaredClasses()
399   {
400     memberAccessCheck(Member.DECLARED);
401     return getDeclaredClasses(false);
402   }
403
404   Class<?>[] getDeclaredClasses (boolean publicOnly)
405   {
406     return VMClass.getDeclaredClasses (this, publicOnly);
407   }
408
409   /**
410    * Get all the declared constructors of this class. This returns an array of
411    * length 0 if there are no constructors, including for primitive types,
412    * arrays, and interfaces. It does, however, include the default
413    * constructor if one was supplied by the compiler. A security check may
414    * be performed, with <code>checkMemberAccess(this, Member.DECLARED)</code>
415    * as well as <code>checkPackageAccess</code> both having to succeed.
416    *
417    * @return all constructors in this class
418    * @throws SecurityException if the security check fails
419    * @since 1.1
420    */
421   public Constructor<?>[] getDeclaredConstructors()
422   {
423     memberAccessCheck(Member.DECLARED);
424     return getDeclaredConstructors(false);
425   }
426
427   Constructor<?>[] getDeclaredConstructors (boolean publicOnly)
428   {
429     return VMClass.getDeclaredConstructors (this, publicOnly);
430   }
431   
432   /**
433    * Get a field declared in this class, where name is its simple name. The
434    * implicit length field of arrays is not available. A security check may
435    * be performed, with <code>checkMemberAccess(this, Member.DECLARED)</code>
436    * as well as <code>checkPackageAccess</code> both having to succeed.
437    *
438    * @param name the name of the field
439    * @return the field
440    * @throws NoSuchFieldException if the field does not exist
441    * @throws SecurityException if the security check fails
442    * @see #getDeclaredFields()
443    * @since 1.1
444    */
445   public Field getDeclaredField(String name) throws NoSuchFieldException
446   {
447     memberAccessCheck(Member.DECLARED);
448     Field[] fields = getDeclaredFields(false);
449     for (int i = 0; i < fields.length; i++)
450       {
451         if (fields[i].getName().equals(name))
452           return fields[i];
453       }
454     throw new NoSuchFieldException();
455   }
456
457   /**
458    * Get all the declared fields in this class, but not those inherited from
459    * superclasses. This returns an array of length 0 if there are no fields,
460    * including for primitive types. This does not return the implicit length
461    * field of arrays. A security check may be performed, with
462    * <code>checkMemberAccess(this, Member.DECLARED)</code> as well as
463    * <code>checkPackageAccess</code> both having to succeed.
464    *
465    * @return all declared fields in this class
466    * @throws SecurityException if the security check fails
467    * @since 1.1
468    */
469   public Field[] getDeclaredFields()
470   {
471     memberAccessCheck(Member.DECLARED);
472     return getDeclaredFields(false);
473   }
474
475   Field[] getDeclaredFields (boolean publicOnly)
476   {
477     return VMClass.getDeclaredFields (this, publicOnly);
478   }
479
480   /**
481    * Get a method declared in this class, where name is its simple name. The
482    * implicit methods of Object are not available from arrays or interfaces.
483    * Constructors (named "&lt;init&gt;" in the class file) and class initializers
484    * (name "&lt;clinit&gt;") are not available.  The Virtual Machine allows
485    * multiple methods with the same signature but differing return types; in
486    * such a case the most specific return types are favored, then the final
487    * choice is arbitrary. If the method takes no argument, an array of zero
488    * elements and null are equivalent for the types argument. A security
489    * check may be performed, with
490    * <code>checkMemberAccess(this, Member.DECLARED)</code> as well as
491    * <code>checkPackageAccess</code> both having to succeed.
492    *
493    * @param methodName the name of the method
494    * @param types the type of each parameter
495    * @return the method
496    * @throws NoSuchMethodException if the method does not exist
497    * @throws SecurityException if the security check fails
498    * @see #getDeclaredMethods()
499    * @since 1.1
500    */
501   public Method getDeclaredMethod(String methodName, Class<?>... types)
502     throws NoSuchMethodException
503   {
504     memberAccessCheck(Member.DECLARED);
505     Method match = matchMethod(getDeclaredMethods(false), methodName, types);
506     if (match == null)
507       throw new NoSuchMethodException(methodName);
508     return match;
509   }
510
511   /**
512    * Get all the declared methods in this class, but not those inherited from
513    * superclasses. This returns an array of length 0 if there are no methods,
514    * including for primitive types. This does include the implicit methods of
515    * arrays and interfaces which mirror methods of Object, nor does it
516    * include constructors or the class initialization methods. The Virtual
517    * Machine allows multiple methods with the same signature but differing
518    * return types; all such methods are in the returned array. A security
519    * check may be performed, with
520    * <code>checkMemberAccess(this, Member.DECLARED)</code> as well as
521    * <code>checkPackageAccess</code> both having to succeed.
522    *
523    * @return all declared methods in this class
524    * @throws SecurityException if the security check fails
525    * @since 1.1
526    */
527   public Method[] getDeclaredMethods()
528   {
529     memberAccessCheck(Member.DECLARED);
530     return getDeclaredMethods(false);
531   }
532
533   Method[] getDeclaredMethods (boolean publicOnly)
534   {
535     return VMClass.getDeclaredMethods (this, publicOnly);
536   }
537  
538   /**
539    * If this is a nested or inner class, return the class that declared it.
540    * If not, return null.
541    *
542    * @return the declaring class of this class
543    * @since 1.1
544    */
545   public Class<?> getDeclaringClass()
546   {
547     return VMClass.getDeclaringClass (this);
548   }
549
550   /**
551    * Get a public field declared or inherited in this class, where name is
552    * its simple name. If the class contains multiple accessible fields by
553    * that name, an arbitrary one is returned. The implicit length field of
554    * arrays is not available. A security check may be performed, with
555    * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
556    * <code>checkPackageAccess</code> both having to succeed.
557    *
558    * @param fieldName the name of the field
559    * @return the field
560    * @throws NoSuchFieldException if the field does not exist
561    * @throws SecurityException if the security check fails
562    * @see #getFields()
563    * @since 1.1
564    */
565   public Field getField(String fieldName)
566     throws NoSuchFieldException
567   {
568     memberAccessCheck(Member.PUBLIC);
569     Field field = internalGetField(fieldName);
570     if (field == null)
571       throw new NoSuchFieldException(fieldName);
572     return field;
573   }
574
575   /**
576    * Get all the public fields declared in this class or inherited from
577    * superclasses. This returns an array of length 0 if there are no fields,
578    * including for primitive types. This does not return the implicit length
579    * field of arrays. A security check may be performed, with
580    * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
581    * <code>checkPackageAccess</code> both having to succeed.
582    *
583    * @return all public fields in this class
584    * @throws SecurityException if the security check fails
585    * @since 1.1
586    */
587   public Field[] getFields()
588   {
589     memberAccessCheck(Member.PUBLIC);
590     return internalGetFields();
591   }
592
593   /**
594    * Like <code>getFields()</code> but without the security checks.
595    */
596   private Field[] internalGetFields()
597   {
598     HashSet<Field> set = new HashSet<Field>();
599     set.addAll(Arrays.asList(getDeclaredFields(true)));
600     Class[] interfaces = getInterfaces();
601     for (int i = 0; i < interfaces.length; i++)
602       set.addAll(Arrays.asList(interfaces[i].internalGetFields()));
603     Class superClass = getSuperclass();
604     if (superClass != null)
605       set.addAll(Arrays.asList(superClass.internalGetFields()));
606     return set.toArray(new Field[set.size()]);
607   }
608
609   /**
610    * Returns the <code>Package</code> in which this class is defined
611    * Returns null when this information is not available from the
612    * classloader of this class.
613    *
614    * @return the package for this class, if it is available
615    * @since 1.2
616    */
617   public Package getPackage()
618   {
619     ClassLoader cl = getClassLoader();
620     if (cl != null)
621       return cl.getPackage(getPackagePortion(getName()));
622     else
623       return VMClassLoader.getPackage(getPackagePortion(getName()));
624   }
625
626   /**
627    * Get the interfaces this class <em>directly</em> implements, in the
628    * order that they were declared. This returns an empty array, not null,
629    * for Object, primitives, void, and classes or interfaces with no direct
630    * superinterface. Array types return Cloneable and Serializable.
631    *
632    * @return the interfaces this class directly implements
633    */
634   public Class<?>[] getInterfaces()
635   {
636     return VMClass.getInterfaces (this);
637   }
638
639   private static final class MethodKey
640   {
641     private String name;
642     private Class[] params;
643     private Class returnType;
644     private int hash;
645     
646     MethodKey(Method m)
647     {
648       name = m.getName();
649       params = m.getParameterTypes();
650       returnType = m.getReturnType();
651       hash = name.hashCode() ^ returnType.hashCode();
652       for(int i = 0; i < params.length; i++)
653         {
654           hash ^= params[i].hashCode();
655         }
656     }
657     
658     public boolean equals(Object o)
659     {
660       if (o instanceof MethodKey)
661         {
662           MethodKey m = (MethodKey) o;
663           if (m.name.equals(name) && m.params.length == params.length
664               && m.returnType == returnType)
665             {
666               for (int i = 0; i < params.length; i++)
667                 {
668                   if (m.params[i] != params[i])
669                     return false;
670                 }
671               return true;
672             }
673         }
674       return false;
675     }
676     
677     public int hashCode()
678     {
679       return hash;
680     }
681   }
682   
683   /**
684    * Get a public method declared or inherited in this class, where name is
685    * its simple name. The implicit methods of Object are not available from
686    * interfaces.  Constructors (named "&lt;init&gt;" in the class file) and class
687    * initializers (name "&lt;clinit&gt;") are not available.  The Virtual
688    * Machine allows multiple methods with the same signature but differing
689    * return types, and the class can inherit multiple methods of the same
690    * return type; in such a case the most specific return types are favored,
691    * then the final choice is arbitrary. If the method takes no argument, an
692    * array of zero elements and null are equivalent for the types argument.
693    * A security check may be performed, with
694    * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
695    * <code>checkPackageAccess</code> both having to succeed.
696    *
697    * @param methodName the name of the method
698    * @param types the type of each parameter
699    * @return the method
700    * @throws NoSuchMethodException if the method does not exist
701    * @throws SecurityException if the security check fails
702    * @see #getMethods()
703    * @since 1.1
704    */
705   public Method getMethod(String methodName, Class<?>... types)
706     throws NoSuchMethodException
707   {
708     memberAccessCheck(Member.PUBLIC);
709     Method method = internalGetMethod(methodName, types);
710     if (method == null)
711       throw new NoSuchMethodException(methodName);
712     return method;
713   }
714
715   /**
716    * Like <code>getMethod(String,Class[])</code> but without the security
717    * checks and returns null instead of throwing NoSuchMethodException.
718    */
719   private Method internalGetMethod(String methodName, Class[] args)
720   {
721     Method match = matchMethod(getDeclaredMethods(true), methodName, args);
722     if (match != null)
723       return match;
724     Class superClass = getSuperclass();
725     if (superClass != null)
726       {
727         match = superClass.internalGetMethod(methodName, args);
728         if(match != null)
729           return match;
730       }
731     Class[] interfaces = getInterfaces();
732     for (int i = 0; i < interfaces.length; i++)
733       {
734         match = interfaces[i].internalGetMethod(methodName, args);
735         if (match != null)
736           return match;
737       }
738     return null;
739   }
740
741   /** 
742    * Find the best matching method in <code>list</code> according to
743    * the definition of ``best matching'' used by <code>getMethod()</code>
744    *
745    * <p>
746    * Returns the method if any, otherwise <code>null</code>.
747    *
748    * @param list List of methods to search
749    * @param name Name of method
750    * @param args Method parameter types
751    * @see #getMethod(String, Class[])
752    */
753   private static Method matchMethod(Method[] list, String name, Class[] args)
754   {
755     Method match = null;
756     for (int i = 0; i < list.length; i++)
757       {
758         Method method = list[i];
759         if (!method.getName().equals(name))
760           continue;
761         if (!matchParameters(args, method.getParameterTypes()))
762           continue;
763         if (match == null
764             || match.getReturnType().isAssignableFrom(method.getReturnType()))
765           match = method;
766       }
767     return match;
768   }
769
770   /**
771    * Check for an exact match between parameter type lists.
772    * Either list may be <code>null</code> to mean a list of
773    * length zero.
774    */
775   private static boolean matchParameters(Class[] types1, Class[] types2)
776   {
777     if (types1 == null)
778       return types2 == null || types2.length == 0;
779     if (types2 == null)
780       return types1 == null || types1.length == 0;
781     if (types1.length != types2.length)
782       return false;
783     for (int i = 0; i < types1.length; i++)
784       {
785         if (types1[i] != types2[i])
786           return false;
787       }
788     return true;
789   }
790   
791   /**
792    * Get all the public methods declared in this class or inherited from
793    * superclasses. This returns an array of length 0 if there are no methods,
794    * including for primitive types. This does not include the implicit
795    * methods of interfaces which mirror methods of Object, nor does it
796    * include constructors or the class initialization methods. The Virtual
797    * Machine allows multiple methods with the same signature but differing
798    * return types; all such methods are in the returned array. A security
799    * check may be performed, with
800    * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
801    * <code>checkPackageAccess</code> both having to succeed.
802    *
803    * @return all public methods in this class
804    * @throws SecurityException if the security check fails
805    * @since 1.1
806    */
807   public Method[] getMethods()
808   {
809     memberAccessCheck(Member.PUBLIC);
810     // NOTE the API docs claim that no methods are returned for arrays,
811     // but Sun's implementation *does* return the public methods of Object
812     // (as would be expected), so we follow their implementation instead
813     // of their documentation.
814     return internalGetMethods();
815   }
816
817   /**
818    * Like <code>getMethods()</code> but without the security checks.
819    */
820   private Method[] internalGetMethods()
821   {
822     HashMap<MethodKey,Method> map = new HashMap<MethodKey,Method>();
823     Method[] methods;
824     Class[] interfaces = getInterfaces();
825     for(int i = 0; i < interfaces.length; i++)
826       {
827         methods = interfaces[i].internalGetMethods();
828         for(int j = 0; j < methods.length; j++)
829           {
830             map.put(new MethodKey(methods[j]), methods[j]);
831           }
832       }
833     Class superClass = getSuperclass();
834     if(superClass != null)
835       {
836         methods = superClass.internalGetMethods();
837         for(int i = 0; i < methods.length; i++)
838           {
839             map.put(new MethodKey(methods[i]), methods[i]);
840           }
841       }
842     methods = getDeclaredMethods(true);
843     for(int i = 0; i < methods.length; i++)
844       {
845         map.put(new MethodKey(methods[i]), methods[i]);
846       }
847     return map.values().toArray(new Method[map.size()]);
848   }
849
850   /**
851    * Get the modifiers of this class.  These can be decoded using Modifier,
852    * and is limited to one of public, protected, or private, and any of
853    * final, static, abstract, or interface. An array class has the same
854    * public, protected, or private modifier as its component type, and is
855    * marked final but not an interface. Primitive types and void are marked
856    * public and final, but not an interface.
857    *
858    * @return the modifiers of this class
859    * @see Modifier
860    * @since 1.1
861    */
862   public int getModifiers()
863   {
864     int mod = VMClass.getModifiers (this, false);
865     return (mod & (Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE |
866           Modifier.FINAL | Modifier.STATIC | Modifier.ABSTRACT |
867           Modifier.INTERFACE));
868   }
869   
870   /**
871    * Get the name of this class, separated by dots for package separators.
872    * If the class represents a primitive type, or void, then the
873    * name of the type as it appears in the Java programming language
874    * is returned.  For instance, <code>Byte.TYPE.getName()</code>
875    * returns "byte".
876    *
877    * Arrays are specially encoded as shown on this table.
878    * <pre>
879    * array type          [<em>element type</em>
880    *                     (note that the element type is encoded per
881    *                      this table)
882    * boolean             Z
883    * byte                B
884    * char                C
885    * short               S
886    * int                 I
887    * long                J
888    * float               F
889    * double              D
890    * void                V
891    * class or interface, alone: &lt;dotted name&gt;
892    * class or interface, as element type: L&lt;dotted name&gt;;
893    * </pre>
894    *
895    * @return the name of this class
896    */
897   public String getName()
898   { 
899     return VMClass.getName (this);
900   }
901
902   /**
903    * Get a resource URL using this class's package using the
904    * getClassLoader().getResource() method.  If this class was loaded using
905    * the system classloader, ClassLoader.getSystemResource() is used instead.
906    *
907    * <p>If the name you supply is absolute (it starts with a <code>/</code>),
908    * then the leading <code>/</code> is removed and it is passed on to
909    * getResource(). If it is relative, the package name is prepended, and
910    * <code>.</code>'s are replaced with <code>/</code>.
911    *
912    * <p>The URL returned is system- and classloader-dependent, and could
913    * change across implementations.
914    *
915    * @param resourceName the name of the resource, generally a path
916    * @return the URL to the resource
917    * @throws NullPointerException if name is null
918    * @since 1.1
919    */
920   public URL getResource(String resourceName)
921   {
922     String name = resourcePath(resourceName);
923     ClassLoader loader = getClassLoader();
924     if (loader == null)
925       return ClassLoader.getSystemResource(name);
926     return loader.getResource(name);
927   }
928
929   /**
930    * Get a resource using this class's package using the
931    * getClassLoader().getResourceAsStream() method.  If this class was loaded
932    * using the system classloader, ClassLoader.getSystemResource() is used
933    * instead.
934    *
935    * <p>If the name you supply is absolute (it starts with a <code>/</code>),
936    * then the leading <code>/</code> is removed and it is passed on to
937    * getResource(). If it is relative, the package name is prepended, and
938    * <code>.</code>'s are replaced with <code>/</code>.
939    *
940    * <p>The URL returned is system- and classloader-dependent, and could
941    * change across implementations.
942    *
943    * @param resourceName the name of the resource, generally a path
944    * @return an InputStream with the contents of the resource in it, or null
945    * @throws NullPointerException if name is null
946    * @since 1.1
947    */
948   public InputStream getResourceAsStream(String resourceName)
949   {
950     String name = resourcePath(resourceName);
951     ClassLoader loader = getClassLoader();
952     if (loader == null)
953       return ClassLoader.getSystemResourceAsStream(name);
954     return loader.getResourceAsStream(name);
955   }
956
957   private String resourcePath(String resourceName)
958   {
959     if (resourceName.length() > 0)
960       {
961         if (resourceName.charAt(0) != '/')
962           {
963             String pkg = getPackagePortion(getName());
964             if (pkg.length() > 0)
965               resourceName = pkg.replace('.','/') + '/' + resourceName;
966           }
967         else
968           {
969             resourceName = resourceName.substring(1);
970           }
971       }
972     return resourceName;
973   }
974
975   /**
976    * Get the signers of this class. This returns null if there are no signers,
977    * such as for primitive types or void.
978    *
979    * @return the signers of this class
980    * @since 1.1
981    */
982   public Object[] getSigners()
983   {
984     return signers == null ? null : (Object[]) signers.clone ();
985   }
986   
987   /**
988    * Set the signers of this class.
989    *
990    * @param signers the signers of this class
991    */
992   void setSigners(Object[] signers)
993   {
994     this.signers = signers;
995   }
996
997   /**
998    * Get the direct superclass of this class.  If this is an interface,
999    * Object, a primitive type, or void, it will return null. If this is an
1000    * array type, it will return Object.
1001    *
1002    * @return the direct superclass of this class
1003    */
1004   public Class<? super T> getSuperclass()
1005   {
1006     return VMClass.getSuperclass (this);
1007   }
1008   
1009   /**
1010    * Return whether this class is an array type.
1011    *
1012    * @return whether this class is an array type
1013    * @since 1.1
1014    */
1015   public boolean isArray()
1016   {
1017     return VMClass.isArray (this);
1018   }
1019   
1020   /**
1021    * Discover whether an instance of the Class parameter would be an
1022    * instance of this Class as well.  Think of doing
1023    * <code>isInstance(c.newInstance())</code> or even
1024    * <code>c.newInstance() instanceof (this class)</code>. While this
1025    * checks widening conversions for objects, it must be exact for primitive
1026    * types.
1027    *
1028    * @param c the class to check
1029    * @return whether an instance of c would be an instance of this class
1030    *         as well
1031    * @throws NullPointerException if c is null
1032    * @since 1.1
1033    */
1034   public boolean isAssignableFrom(Class<?> c)
1035   {
1036     return VMClass.isAssignableFrom (this, c);
1037   }
1038  
1039   /**
1040    * Discover whether an Object is an instance of this Class.  Think of it
1041    * as almost like <code>o instanceof (this class)</code>.
1042    *
1043    * @param o the Object to check
1044    * @return whether o is an instance of this class
1045    * @since 1.1
1046    */
1047   public boolean isInstance(Object o)
1048   {
1049     return VMClass.isInstance (this, o);
1050   }
1051   
1052   /**
1053    * Check whether this class is an interface or not.  Array types are not
1054    * interfaces.
1055    *
1056    * @return whether this class is an interface or not
1057    */
1058   public boolean isInterface()
1059   {
1060     return VMClass.isInterface (this);
1061   }
1062   
1063   /**
1064    * Return whether this class is a primitive type.  A primitive type class
1065    * is a class representing a kind of "placeholder" for the various
1066    * primitive types, or void.  You can access the various primitive type
1067    * classes through java.lang.Boolean.TYPE, java.lang.Integer.TYPE, etc.,
1068    * or through boolean.class, int.class, etc.
1069    *
1070    * @return whether this class is a primitive type
1071    * @see Boolean#TYPE
1072    * @see Byte#TYPE
1073    * @see Character#TYPE
1074    * @see Short#TYPE
1075    * @see Integer#TYPE
1076    * @see Long#TYPE
1077    * @see Float#TYPE
1078    * @see Double#TYPE
1079    * @see Void#TYPE
1080    * @since 1.1
1081    */
1082   public boolean isPrimitive()
1083   {
1084     return VMClass.isPrimitive (this);
1085   }
1086   
1087   /**
1088    * Get a new instance of this class by calling the no-argument constructor.
1089    * The class is initialized if it has not been already. A security check
1090    * may be performed, with <code>checkMemberAccess(this, Member.PUBLIC)</code>
1091    * as well as <code>checkPackageAccess</code> both having to succeed.
1092    *
1093    * @return a new instance of this class
1094    * @throws InstantiationException if there is not a no-arg constructor
1095    *         for this class, including interfaces, abstract classes, arrays,
1096    *         primitive types, and void; or if an exception occurred during
1097    *         the constructor
1098    * @throws IllegalAccessException if you are not allowed to access the
1099    *         no-arg constructor because of scoping reasons
1100    * @throws SecurityException if the security check fails
1101    * @throws ExceptionInInitializerError if class initialization caused by
1102    *         this call fails with an exception
1103    */
1104   public T newInstance()
1105     throws InstantiationException, IllegalAccessException
1106   {
1107     memberAccessCheck(Member.PUBLIC);
1108     Constructor<T> constructor;
1109     synchronized(this)
1110       {
1111         constructor = this.constructor;
1112       }
1113     if (constructor == null)
1114       {
1115         Constructor[] constructors = getDeclaredConstructors(false);
1116         for (int i = 0; i < constructors.length; i++)
1117           {
1118             if (constructors[i].getParameterTypes().length == 0)
1119               {
1120                 constructor = constructors[i];
1121                 break;
1122               }
1123           }
1124         if (constructor == null)
1125           throw new InstantiationException(getName());
1126         if (!Modifier.isPublic(constructor.getModifiers())
1127             || !Modifier.isPublic(VMClass.getModifiers(this, true)))
1128           {
1129             final Constructor finalConstructor = constructor;
1130             AccessController.doPrivileged(new PrivilegedAction()
1131               {
1132                 public Object run()
1133                 {
1134                   finalConstructor.setAccessible(true);
1135                   return null;
1136                 }
1137               });
1138           }
1139         synchronized(this)
1140           {
1141             if (this.constructor == null)
1142               this.constructor = constructor;
1143           }         
1144       }
1145     int modifiers = constructor.getModifiers();
1146     if (!Modifier.isPublic(modifiers)
1147         || !Modifier.isPublic(VMClass.getModifiers(this, true)))
1148       {
1149         Class caller = VMStackWalker.getCallingClass();
1150         if (caller != null &&
1151             caller != this &&
1152             (Modifier.isPrivate(modifiers)
1153              || getClassLoader() != caller.getClassLoader()
1154              || !getPackagePortion(getName())
1155              .equals(getPackagePortion(caller.getName()))))
1156           throw new IllegalAccessException(getName()
1157                                            + " has an inaccessible constructor");
1158       }
1159     try
1160       {
1161         return constructor.newInstance(null);
1162       }
1163     catch (InvocationTargetException e)
1164       {
1165         VMClass.throwException(e.getTargetException());
1166         throw (InternalError) new InternalError
1167           ("VMClass.throwException returned").initCause(e);
1168       }
1169   }
1170
1171   /**
1172    * Returns the protection domain of this class. If the classloader did not
1173    * record the protection domain when creating this class the unknown
1174    * protection domain is returned which has a <code>null</code> code source
1175    * and all permissions. A security check may be performed, with
1176    * <code>RuntimePermission("getProtectionDomain")</code>.
1177    *
1178    * @return the protection domain
1179    * @throws SecurityException if the security manager exists and the caller
1180    * does not have <code>RuntimePermission("getProtectionDomain")</code>.
1181    * @see RuntimePermission
1182    * @since 1.2
1183    */
1184   public ProtectionDomain getProtectionDomain()
1185   {
1186     SecurityManager sm = SecurityManager.current;
1187     if (sm != null)
1188       sm.checkPermission(new RuntimePermission("getProtectionDomain"));
1189
1190     return pd == null ? StaticData.unknownProtectionDomain : pd;
1191   }
1192
1193   /**
1194    * Return the human-readable form of this Object.  For an object, this
1195    * is either "interface " or "class " followed by <code>getName()</code>,
1196    * for primitive types and void it is just <code>getName()</code>.
1197    *
1198    * @return the human-readable form of this Object
1199    */
1200   public String toString()
1201   {
1202     if (isPrimitive())
1203       return getName();
1204     return (isInterface() ? "interface " : "class ") + getName();
1205   }
1206
1207   /**
1208    * Returns the desired assertion status of this class, if it were to be
1209    * initialized at this moment. The class assertion status, if set, is
1210    * returned; the backup is the default package status; then if there is
1211    * a class loader, that default is returned; and finally the system default
1212    * is returned. This method seldom needs calling in user code, but exists
1213    * for compilers to implement the assert statement. Note that there is no
1214    * guarantee that the result of this method matches the class's actual
1215    * assertion status.
1216    *
1217    * @return the desired assertion status
1218    * @see ClassLoader#setClassAssertionStatus(String, boolean)
1219    * @see ClassLoader#setPackageAssertionStatus(String, boolean)
1220    * @see ClassLoader#setDefaultAssertionStatus(boolean)
1221    * @since 1.4
1222    */
1223   public boolean desiredAssertionStatus()
1224   {
1225     ClassLoader c = getClassLoader();
1226     Object status;
1227     if (c == null)
1228       return VMClassLoader.defaultAssertionStatus();
1229     if (c.classAssertionStatus != null)
1230       synchronized (c)
1231         {
1232           status = c.classAssertionStatus.get(getName());
1233           if (status != null)
1234             return status.equals(Boolean.TRUE);
1235         }
1236     else
1237       {
1238         status = ClassLoader.StaticData.
1239                     systemClassAssertionStatus.get(getName());
1240         if (status != null)
1241           return status.equals(Boolean.TRUE);
1242       }
1243     if (c.packageAssertionStatus != null)
1244       synchronized (c)
1245         {
1246           String name = getPackagePortion(getName());
1247           if ("".equals(name))
1248             status = c.packageAssertionStatus.get(null);
1249           else
1250             do
1251               {
1252                 status = c.packageAssertionStatus.get(name);
1253                 name = getPackagePortion(name);
1254               }
1255             while (! "".equals(name) && status == null);
1256           if (status != null)
1257             return status.equals(Boolean.TRUE);
1258         }
1259     else
1260       {
1261         String name = getPackagePortion(getName());
1262         if ("".equals(name))
1263           status = ClassLoader.StaticData.
1264                     systemPackageAssertionStatus.get(null);
1265         else
1266           do
1267             {
1268               status = ClassLoader.StaticData.
1269                         systemPackageAssertionStatus.get(name);
1270               name = getPackagePortion(name);
1271             }
1272           while (! "".equals(name) && status == null);
1273         if (status != null)
1274           return status.equals(Boolean.TRUE);
1275       }
1276     return c.defaultAssertionStatus;
1277   }
1278
1279   /**
1280    * <p>
1281    * Casts this class to represent a subclass of the specified class.
1282    * This method is useful for `narrowing' the type of a class so that
1283    * the class object, and instances of that class, can match the contract
1284    * of a more restrictive method.  For example, if this class has the
1285    * static type of <code>Class&lt;Object&gt;</code>, and a dynamic type of
1286    * <code>Class&lt;Rectangle&gt;</code>, then, assuming <code>Shape</code> is
1287    * a superclass of <code>Rectangle</code>, this method can be used on
1288    * this class with the parameter, <code>Class&lt;Shape&gt;</code>, to retain
1289    * the same instance but with the type
1290    * <code>Class&lt;? extends Shape&gt;</code>.
1291    * </p>
1292    * <p>
1293    * If this class can be converted to an instance which is parameterised
1294    * over a subtype of the supplied type, <code>U</code>, then this method
1295    * returns an appropriately cast reference to this object.  Otherwise,
1296    * a <code>ClassCastException</code> is thrown.
1297    * </p>
1298    * 
1299    * @param klass the class object, the parameterized type (<code>U</code>) of
1300    *              which should be a superclass of the parameterized type of
1301    *              this instance.
1302    * @return a reference to this object, appropriately cast.
1303    * @throws ClassCastException if this class can not be converted to one
1304    *                            which represents a subclass of the specified
1305    *                            type, <code>U</code>. 
1306    * @since 1.5
1307    */
1308   public <U> Class<? extends U> asSubclass(Class<U> klass)
1309   {
1310     if (! klass.isAssignableFrom(this))
1311       throw new ClassCastException();
1312     return (Class<? extends U>) this;
1313   }
1314
1315   /**
1316    * Returns the specified object, cast to this <code>Class</code>' type.
1317    *
1318    * @param obj the object to cast
1319    * @throws ClassCastException  if obj is not an instance of this class
1320    * @since 1.5
1321    */
1322   public T cast(Object obj)
1323   {
1324     if (obj != null && ! isInstance(obj))
1325       throw new ClassCastException();
1326     return (T) obj;
1327   }
1328
1329   /**
1330    * Like <code>getField(String)</code> but without the security checks and
1331    * returns null instead of throwing NoSuchFieldException.
1332    */
1333   private Field internalGetField(String name)
1334   {
1335     Field[] fields = getDeclaredFields(true);
1336     for (int i = 0; i < fields.length; i++)
1337       {
1338         Field field = fields[i];
1339         if (field.getName().equals(name))
1340           return field;
1341       }
1342     Class[] interfaces = getInterfaces();
1343     for (int i = 0; i < interfaces.length; i++)
1344       {
1345         Field field = interfaces[i].internalGetField(name);
1346         if(field != null)
1347           return field;
1348       }
1349     Class superClass = getSuperclass();
1350     if (superClass != null)
1351       return superClass.internalGetField(name);
1352     return null;
1353   }
1354
1355   /**
1356    * Strip the last portion of the name (after the last dot).
1357    *
1358    * @param name the name to get package of
1359    * @return the package name, or "" if no package
1360    */
1361   private static String getPackagePortion(String name)
1362   {
1363     int lastInd = name.lastIndexOf('.');
1364     if (lastInd == -1)
1365       return "";
1366     return name.substring(0, lastInd);
1367   }
1368
1369   /**
1370    * Perform security checks common to all of the methods that
1371    * get members of this Class.
1372    */
1373   private void memberAccessCheck(int which)
1374   {
1375     SecurityManager sm = SecurityManager.current;
1376     if (sm != null)
1377       {
1378         sm.checkMemberAccess(this, which);
1379         Package pkg = getPackage();
1380         if (pkg != null)
1381           sm.checkPackageAccess(pkg.getName());
1382       }
1383   }
1384
1385   /**
1386    * Returns the enumeration constants of this class, or
1387    * null if this class is not an <code>Enum</code>.
1388    *
1389    * @return an array of <code>Enum</code> constants
1390    *         associated with this class, or null if this
1391    *         class is not an <code>enum</code>.
1392    * @since 1.5
1393    */
1394   public T[] getEnumConstants()
1395   {
1396     if (isEnum())
1397       {
1398         try
1399           {
1400             return (T[]) getMethod("values").invoke(null);
1401           }
1402         catch (NoSuchMethodException exception)
1403           {
1404             throw new Error("Enum lacks values() method");
1405           }
1406         catch (IllegalAccessException exception)
1407           {
1408             throw new Error("Unable to access Enum class");
1409           }
1410         catch (InvocationTargetException exception)
1411           {
1412             throw new
1413               RuntimeException("The values method threw an exception",
1414                                exception);
1415           }
1416       }
1417     else
1418       {
1419         return null;
1420       }
1421   }
1422
1423   /**
1424    * Returns true if this class is an <code>Enum</code>.
1425    *
1426    * @return true if this is an enumeration class.
1427    * @since 1.5
1428    */
1429   public boolean isEnum()
1430   {
1431     int mod = VMClass.getModifiers (this, true);
1432     return (mod & ENUM) != 0;
1433   }
1434
1435   /**
1436    * Returns true if this class is a synthetic class, generated by
1437    * the compiler.
1438    *
1439    * @return true if this is a synthetic class.
1440    * @since 1.5
1441    */
1442   public boolean isSynthetic()
1443   {
1444     int mod = VMClass.getModifiers (this, true);
1445     return (mod & SYNTHETIC) != 0;
1446   }
1447
1448   /**
1449    * Returns true if this class is an <code>Annotation</code>.
1450    *
1451    * @return true if this is an annotation class.
1452    * @since 1.5
1453    */
1454   public boolean isAnnotation()
1455   {
1456     int mod = VMClass.getModifiers (this, true);
1457     return (mod & ANNOTATION) != 0;
1458   }
1459
1460   /**
1461    * Returns the simple name for this class, as used in the source
1462    * code.  For normal classes, this is the content returned by
1463    * <code>getName()</code> which follows the last ".".  Anonymous
1464    * classes have no name, and so the result of calling this method is
1465    * "".  The simple name of an array consists of the simple name of
1466    * its component type, followed by "[]".  Thus, an array with the 
1467    * component type of an anonymous class has a simple name of simply
1468    * "[]".
1469    *
1470    * @return the simple name for this class.
1471    * @since 1.5
1472    */
1473   public String getSimpleName()
1474   {
1475     return VMClass.getSimpleName(this);
1476   }
1477
1478   /**
1479    * Returns this class' annotation for the specified annotation type,
1480    * or <code>null</code> if no such annotation exists.
1481    *
1482    * @param annotationClass the type of annotation to look for.
1483    * @return this class' annotation for the specified type, or
1484    *         <code>null</code> if no such annotation exists.
1485    * @since 1.5
1486    */
1487   public <A extends Annotation> A getAnnotation(Class<A> annotationClass)
1488   {
1489     A foundAnnotation = null;
1490     Annotation[] annotations = getAnnotations();
1491     for (Annotation annotation : annotations)
1492       if (annotation.annotationType() == annotationClass)
1493         foundAnnotation = (A) annotation;
1494     return foundAnnotation;
1495   }
1496
1497   /**
1498    * Returns all annotations associated with this class.  If there are
1499    * no annotations associated with this class, then a zero-length array
1500    * will be returned.  The returned array may be modified by the client
1501    * code, but this will have no effect on the annotation content of this
1502    * class, and hence no effect on the return value of this method for
1503    * future callers.
1504    *
1505    * @return this class' annotations.
1506    * @since 1.5
1507    */
1508   public Annotation[] getAnnotations()
1509   {
1510     HashMap<Class, Annotation> map = new HashMap<Class, Annotation>();
1511     for (Annotation a : getDeclaredAnnotations())
1512       map.put((Class) a.annotationType(), a);
1513     for (Class<? super T> s = getSuperclass();
1514          s != null;
1515          s = s.getSuperclass())
1516       {
1517         for (Annotation a : s.getDeclaredAnnotations())
1518           {
1519             Class k = (Class) a.annotationType();
1520             if (! map.containsKey(k) && k.isAnnotationPresent(Inherited.class))
1521               map.put(k, a);
1522           }
1523       }
1524     Collection<Annotation> v = map.values();
1525     return v.toArray(new Annotation[v.size()]);
1526   }
1527
1528   /**
1529    * <p>
1530    * Returns the canonical name of this class, as defined by section
1531    * 6.7 of the Java language specification.  Each package, top-level class,
1532    * top-level interface and primitive type has a canonical name.  A member
1533    * class has a canonical name, if its parent class has one.  Likewise,
1534    * an array type has a canonical name, if its component type does.
1535    * Local or anonymous classes do not have canonical names.
1536    * </p>
1537    * <p>
1538    * The canonical name for top-level classes, top-level interfaces and
1539    * primitive types is always the same as the fully-qualified name.
1540    * For array types, the canonical name is the canonical name of its
1541    * component type with `[]' appended.  
1542    * </p>
1543    * <p>
1544    * The canonical name of a member class always refers to the place where
1545    * the class was defined, and is composed of the canonical name of the
1546    * defining class and the simple name of the member class, joined by `.'.
1547    *  For example, if a <code>Person</code> class has an inner class,
1548    * <code>M</code>, then both its fully-qualified name and canonical name
1549    * is <code>Person.M</code>.  A subclass, <code>Staff</code>, of
1550    * <code>Person</code> refers to the same inner class by the fully-qualified
1551    * name of <code>Staff.M</code>, but its canonical name is still
1552    * <code>Person.M</code>.
1553    * </p>
1554    * <p>
1555    * Where no canonical name is present, <code>null</code> is returned.
1556    * </p>
1557    *
1558    * @return the canonical name of the class, or <code>null</code> if the
1559    *         class doesn't have a canonical name.
1560    * @since 1.5
1561    */
1562   public String getCanonicalName()
1563   {
1564     return VMClass.getCanonicalName(this);
1565   }
1566
1567   /**
1568    * Returns all annotations directly defined by this class.  If there are
1569    * no annotations associated with this class, then a zero-length array
1570    * will be returned.  The returned array may be modified by the client
1571    * code, but this will have no effect on the annotation content of this
1572    * class, and hence no effect on the return value of this method for
1573    * future callers.
1574    *
1575    * @return the annotations directly defined by this class.
1576    * @since 1.5
1577    */
1578   public Annotation[] getDeclaredAnnotations()
1579   {
1580     return VMClass.getDeclaredAnnotations(this);
1581   }
1582
1583   /**
1584    * Returns the class which immediately encloses this class.  If this class
1585    * is a top-level class, this method returns <code>null</code>.
1586    *
1587    * @return the immediate enclosing class, or <code>null</code> if this is
1588    *         a top-level class.
1589    * @since 1.5
1590    */
1591   public Class<?> getEnclosingClass()
1592   {
1593     return VMClass.getEnclosingClass(this);
1594   }
1595
1596   /**
1597    * Returns the constructor which immediately encloses this class.  If
1598    * this class is a top-level class, or a local or anonymous class 
1599    * immediately enclosed by a type definition, instance initializer
1600    * or static initializer, then <code>null</code> is returned.
1601    *
1602    * @return the immediate enclosing constructor if this class is
1603    *         declared within a constructor.  Otherwise, <code>null</code>
1604    *         is returned.
1605    * @since 1.5
1606    */
1607   public Constructor<?> getEnclosingConstructor()
1608   {
1609     return VMClass.getEnclosingConstructor(this);
1610   }
1611
1612   /**
1613    * Returns the method which immediately encloses this class.  If
1614    * this class is a top-level class, or a local or anonymous class 
1615    * immediately enclosed by a type definition, instance initializer
1616    * or static initializer, then <code>null</code> is returned.
1617    *
1618    * @return the immediate enclosing method if this class is
1619    *         declared within a method.  Otherwise, <code>null</code>
1620    *         is returned.
1621    * @since 1.5
1622    */
1623   public Method getEnclosingMethod()
1624   {
1625     return VMClass.getEnclosingMethod(this);
1626   }
1627
1628   /**
1629    * <p>
1630    * Returns an array of <code>Type</code> objects which represent the
1631    * interfaces directly implemented by this class or extended by this
1632    * interface.
1633    * </p>
1634    * <p>
1635    * If one of the superinterfaces is a parameterized type, then the
1636    * object returned for this interface reflects the actual type
1637    * parameters used in the source code.  Type parameters are created
1638    * using the semantics specified by the <code>ParameterizedType</code>
1639    * interface, and only if an instance has not already been created.
1640    * </p>
1641    * <p>
1642    * The order of the interfaces in the array matches the order in which
1643    * the interfaces are declared.  For classes which represent an array,
1644    * an array of two interfaces, <code>Cloneable</code> and
1645    * <code>Serializable</code>, is always returned, with the objects in
1646    * that order.  A class representing a primitive type or void always
1647    * returns an array of zero size.
1648    * </p>
1649    *
1650    * @return an array of interfaces implemented or extended by this class.
1651    * @throws GenericSignatureFormatError if the generic signature of one
1652    *         of the interfaces does not comply with that specified by the Java
1653    *         Virtual Machine specification, 3rd edition.
1654    * @throws TypeNotPresentException if any of the superinterfaces refers
1655    *         to a non-existant type.
1656    * @throws MalformedParameterizedTypeException if any of the interfaces
1657    *         refer to a parameterized type that can not be instantiated for
1658    *         some reason.
1659    * @since 1.5
1660    * @see java.lang.reflect.ParameterizedType
1661    */
1662   public Type[] getGenericInterfaces()
1663   {
1664     if (isPrimitive())
1665       return new Type[0];
1666
1667     String sig = VMClass.getClassSignature(this);
1668     if (sig == null)
1669       return getInterfaces();
1670
1671     ClassSignatureParser p = new ClassSignatureParser(this, sig);
1672     return p.getInterfaceTypes();
1673   }
1674
1675   /**
1676    * <p>
1677    * Returns a <code>Type</code> object representing the direct superclass,
1678    * whether class, interface, primitive type or void, of this class.
1679    * If this class is an array class, then a class instance representing
1680    * the <code>Object</code> class is returned.  If this class is primitive,
1681    * an interface, or a representation of either the <code>Object</code>
1682    * class or void, then <code>null</code> is returned.
1683    * </p>
1684    * <p>
1685    * If the superclass is a parameterized type, then the
1686    * object returned for this interface reflects the actual type
1687    * parameters used in the source code.  Type parameters are created
1688    * using the semantics specified by the <code>ParameterizedType</code>
1689    * interface, and only if an instance has not already been created.
1690    * </p>
1691    *
1692    * @return the superclass of this class.
1693    * @throws GenericSignatureFormatError if the generic signature of the
1694    *         class does not comply with that specified by the Java
1695    *         Virtual Machine specification, 3rd edition.
1696    * @throws TypeNotPresentException if the superclass refers
1697    *         to a non-existant type.
1698    * @throws MalformedParameterizedTypeException if the superclass
1699    *         refers to a parameterized type that can not be instantiated for
1700    *         some reason.
1701    * @since 1.5
1702    * @see java.lang.reflect.ParameterizedType
1703    */
1704   public Type getGenericSuperclass()
1705   {
1706     if (isArray())
1707       return Object.class;
1708
1709     if (isPrimitive() || isInterface() || this == Object.class)
1710       return null;
1711
1712     String sig = VMClass.getClassSignature(this);
1713     if (sig == null)
1714       return getSuperclass();
1715
1716     ClassSignatureParser p = new ClassSignatureParser(this, sig);
1717     return p.getSuperclassType();
1718   }
1719
1720   /**
1721    * Returns an array of <code>TypeVariable</code> objects that represents
1722    * the type variables declared by this class, in declaration order.
1723    * An array of size zero is returned if this class has no type
1724    * variables.
1725    *
1726    * @return the type variables associated with this class. 
1727    * @throws GenericSignatureFormatError if the generic signature does
1728    *         not conform to the format specified in the Virtual Machine
1729    *         specification, version 3.
1730    * @since 1.5
1731    */
1732   public TypeVariable<Class<T>>[] getTypeParameters()
1733   {
1734     String sig = VMClass.getClassSignature(this);
1735     if (sig == null)
1736       return (TypeVariable<Class<T>>[])new TypeVariable[0];
1737
1738     ClassSignatureParser p = new ClassSignatureParser(this, sig);
1739     return p.getTypeParameters();
1740   }
1741
1742   /**
1743    * Returns true if an annotation for the specified type is associated
1744    * with this class.  This is primarily a short-hand for using marker
1745    * annotations.
1746    *
1747    * @param annotationClass the type of annotation to look for.
1748    * @return true if an annotation exists for the specified type.
1749    * @since 1.5
1750    */
1751   public boolean isAnnotationPresent(Class<? extends Annotation> 
1752                                      annotationClass)
1753   {
1754     return getAnnotation(annotationClass) != null;
1755   }
1756
1757   /**
1758    * Returns true if this object represents an anonymous class.
1759    *
1760    * @return true if this object represents an anonymous class.
1761    * @since 1.5
1762    */
1763   public boolean isAnonymousClass()
1764   {
1765     return VMClass.isAnonymousClass(this);
1766   }
1767
1768   /**
1769    * Returns true if this object represents an local class.
1770    *
1771    * @return true if this object represents an local class.
1772    * @since 1.5
1773    */
1774   public boolean isLocalClass()
1775   {
1776     return VMClass.isLocalClass(this);
1777   }
1778
1779   /**
1780    * Returns true if this object represents an member class.
1781    *
1782    * @return true if this object represents an member class.
1783    * @since 1.5
1784    */
1785   public boolean isMemberClass()
1786   {
1787     return VMClass.isMemberClass(this);
1788   }
1789
1790
1791 }