OSDN Git Service

Merged gcj-eclipse branch to trunk.
[pf3gnuchains/gcc-fork.git] / libjava / 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.java.lang.reflect.ClassSignatureParser;
42 import java.io.InputStream;
43 import java.io.Serializable;
44 import java.lang.annotation.Annotation;
45 import java.lang.reflect.Constructor;
46 import java.lang.reflect.Field;
47 import java.lang.reflect.GenericDeclaration;
48 import java.lang.reflect.InvocationTargetException;
49 import java.lang.reflect.Member;
50 import java.lang.reflect.Method;
51 import java.lang.reflect.Type;
52 import java.lang.reflect.TypeVariable;
53 import java.net.URL;
54 import java.security.ProtectionDomain;
55 import java.util.ArrayList;
56 import java.util.Arrays;
57 import java.util.HashSet;
58 import java.util.HashMap;
59 import java.util.Collection;
60 import java.lang.reflect.AnnotatedElement;
61 import java.lang.annotation.Annotation;
62 import java.lang.annotation.Inherited;
63
64 /**
65  * A Class represents a Java type.  There will never be multiple Class
66  * objects with identical names and ClassLoaders. Primitive types, array
67  * types, and void also have a Class object.
68  *
69  * <p>Arrays with identical type and number of dimensions share the same class.
70  * The array class ClassLoader is the same as the ClassLoader of the element
71  * type of the array (which can be null to indicate the bootstrap classloader).
72  * The name of an array class is <code>[&lt;signature format&gt;;</code>.
73  * <p> For example,
74  * String[]'s class is <code>[Ljava.lang.String;</code>. boolean, byte,
75  * short, char, int, long, float and double have the "type name" of
76  * Z,B,S,C,I,J,F,D for the purposes of array classes.  If it's a
77  * multidimensioned array, the same principle applies:
78  * <code>int[][][]</code> == <code>[[[I</code>.
79  *
80  * <p>There is no public constructor - Class objects are obtained only through
81  * the virtual machine, as defined in ClassLoaders.
82  *
83  * @serialData Class objects serialize specially:
84  * <code>TC_CLASS ClassDescriptor</code>. For more serialization information,
85  * see {@link ObjectStreamClass}.
86  *
87  * @author John Keiser
88  * @author Eric Blake (ebb9@email.byu.edu)
89  * @author Tom Tromey (tromey@cygnus.com)
90  * @since 1.0
91  * @see ClassLoader
92  */
93 public final class Class<T>
94   implements Type, AnnotatedElement, GenericDeclaration, Serializable
95 {
96   /**
97    * Class is non-instantiable from Java code; only the VM can create
98    * instances of this class.
99    */
100   private Class ()
101   {
102   }
103
104   // Initialize the class.
105   private native void initializeClass ();
106
107   // finalization
108   protected native void finalize () throws Throwable;
109
110   /**
111    * Use the classloader of the current class to load, link, and initialize
112    * a class. This is equivalent to your code calling
113    * <code>Class.forName(name, true, getClass().getClassLoader())</code>.
114    *
115    * @param name the name of the class to find
116    * @return the Class object representing the class
117    * @throws ClassNotFoundException if the class was not found by the
118    *         classloader
119    * @throws LinkageError if linking the class fails
120    * @throws ExceptionInInitializerError if the class loads, but an exception
121    *         occurs during initialization
122    */
123   public static native Class<?> forName (String className)
124     throws ClassNotFoundException;
125
126   // A private internal method that is called by compiler-generated code.
127   private static Class forName (String className, Class caller)
128     throws ClassNotFoundException
129   {
130     return forName(className, true, caller.getClassLoaderInternal());
131   }
132
133
134   /**
135    * Use the specified classloader to load and link a class. If the loader
136    * is null, this uses the bootstrap class loader (provide the security
137    * check succeeds). Unfortunately, this method cannot be used to obtain
138    * the Class objects for primitive types or for void, you have to use
139    * the fields in the appropriate java.lang wrapper classes.
140    *
141    * <p>Calls <code>classloader.loadclass(name, initialize)</code>.
142    *
143    * @param name the name of the class to find
144    * @param initialize whether or not to initialize the class at this time
145    * @param classloader the classloader to use to find the class; null means
146    *        to use the bootstrap class loader
147    * @throws ClassNotFoundException if the class was not found by the
148    *         classloader
149    * @throws LinkageError if linking the class fails
150    * @throws ExceptionInInitializerError if the class loads, but an exception
151    *         occurs during initialization
152    * @throws SecurityException if the <code>classloader</code> argument
153    *         is <code>null</code> and the caller does not have the
154    *         <code>RuntimePermission("getClassLoader")</code> permission
155    * @see ClassLoader
156    * @since 1.2
157    */
158   public static native Class<?> forName (String className, boolean initialize,
159                                          ClassLoader loader)
160     throws ClassNotFoundException;
161   
162   /**
163    * Get all the public member classes and interfaces declared in this
164    * class or inherited from superclasses. This returns an array of length
165    * 0 if there are no member classes, including for primitive types. A
166    * security check may be performed, with
167    * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
168    * <code>checkPackageAccess</code> both having to succeed.
169    *
170    * @return all public member classes in this class
171    * @throws SecurityException if the security check fails
172    * @since 1.1
173    */
174   public Class<?>[] getClasses()
175   {
176     memberAccessCheck(Member.PUBLIC);
177     return internalGetClasses();
178   }
179
180   /**
181    * Like <code>getClasses()</code> but without the security checks.
182    */
183   private Class<?>[] internalGetClasses()
184   {
185     ArrayList<Class> list = new ArrayList<Class>();
186     list.addAll(Arrays.asList(getDeclaredClasses(true)));
187     Class superClass = getSuperclass();
188     if (superClass != null)
189       list.addAll(Arrays.asList(superClass.internalGetClasses()));
190     return list.toArray(new Class<?>[list.size()]);
191   }
192
193   /**
194    * Get the ClassLoader that loaded this class.  If the class was loaded
195    * by the bootstrap classloader, this method will return null.
196    * If there is a security manager, and the caller's class loader is not
197    * an ancestor of the requested one, a security check of
198    * <code>RuntimePermission("getClassLoader")</code>
199    * must first succeed. Primitive types and void return null.
200    *
201    * @return the ClassLoader that loaded this class
202    * @throws SecurityException if the security check fails
203    * @see ClassLoader
204    * @see RuntimePermission
205    */
206   public native ClassLoader getClassLoader ();
207
208   // A private internal method that is called by compiler-generated code.
209   private final native ClassLoader getClassLoader (Class caller);
210
211   /**
212    *  Internal method that circumvents the usual security checks when 
213    *  getting the class loader.
214    */
215   private native ClassLoader getClassLoaderInternal ();
216
217   /**
218    * If this is an array, get the Class representing the type of array.
219    * Examples: "[[Ljava.lang.String;" would return "[Ljava.lang.String;", and
220    * calling getComponentType on that would give "java.lang.String".  If
221    * this is not an array, returns null.
222    *
223    * @return the array type of this class, or null
224    * @see Array
225    * @since 1.1
226    */
227   public native Class<?> getComponentType ();
228
229   /**
230    * Get a public constructor declared in this class. If the constructor takes
231    * no argument, an array of zero elements and null are equivalent for the
232    * types argument. A security check may be performed, with
233    * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
234    * <code>checkPackageAccess</code> both having to succeed.
235    *
236    * @param types the type of each parameter
237    * @return the constructor
238    * @throws NoSuchMethodException if the constructor does not exist
239    * @throws SecurityException if the security check fails
240    * @see #getConstructors()
241    * @since 1.1
242    */
243   public native Constructor<T> getConstructor(Class<?>... args)
244     throws NoSuchMethodException;
245
246   /**
247    * Get all the public constructors of this class. This returns an array of
248    * length 0 if there are no constructors, including for primitive types,
249    * arrays, and interfaces. It does, however, include the default
250    * constructor if one was supplied by the compiler. A security check may
251    * be performed, with <code>checkMemberAccess(this, Member.PUBLIC)</code>
252    * as well as <code>checkPackageAccess</code> both having to succeed.
253    *
254    * @return all public constructors in this class
255    * @throws SecurityException if the security check fails
256    * @since 1.1
257    */
258   public Constructor<?>[] getConstructors()
259   {
260     memberAccessCheck(Member.PUBLIC);
261     return getDeclaredConstructors(true);
262   }
263
264   /**
265    * Get a constructor declared in this class. If the constructor takes no
266    * argument, an array of zero elements and null are equivalent for the
267    * types argument. A security check may be performed, with
268    * <code>checkMemberAccess(this, Member.DECLARED)</code> as well as
269    * <code>checkPackageAccess</code> both having to succeed.
270    *
271    * @param types the type of each parameter
272    * @return the constructor
273    * @throws NoSuchMethodException if the constructor does not exist
274    * @throws SecurityException if the security check fails
275    * @see #getDeclaredConstructors()
276    * @since 1.1
277    */
278   public native Constructor<T> getDeclaredConstructor(Class<?>... args)
279     throws NoSuchMethodException;
280
281   /**
282    * Get all the declared member classes and interfaces in this class, but
283    * not those inherited from superclasses. This returns an array of length
284    * 0 if there are no member classes, including for primitive types. A
285    * security check may be performed, with
286    * <code>checkMemberAccess(this, Member.DECLARED)</code> as well as
287    * <code>checkPackageAccess</code> both having to succeed.
288    *
289    * @return all declared member classes in this class
290    * @throws SecurityException if the security check fails
291    * @since 1.1
292    */
293   public Class<?>[] getDeclaredClasses()
294   {
295     memberAccessCheck(Member.DECLARED);
296     return getDeclaredClasses(false);
297   }
298
299   native Class<?>[] getDeclaredClasses (boolean publicOnly);
300
301   /**
302    * Get all the declared constructors of this class. This returns an array of
303    * length 0 if there are no constructors, including for primitive types,
304    * arrays, and interfaces. It does, however, include the default
305    * constructor if one was supplied by the compiler. A security check may
306    * be performed, with <code>checkMemberAccess(this, Member.DECLARED)</code>
307    * as well as <code>checkPackageAccess</code> both having to succeed.
308    *
309    * @return all constructors in this class
310    * @throws SecurityException if the security check fails
311    * @since 1.1
312    */
313   public Constructor<?>[] getDeclaredConstructors()
314   {
315     memberAccessCheck(Member.DECLARED);
316     return getDeclaredConstructors(false);
317   }
318
319   native Constructor<?>[] getDeclaredConstructors (boolean publicOnly);
320
321   /**
322    * Get a field declared in this class, where name is its simple name. The
323    * implicit length field of arrays is not available. A security check may
324    * be performed, with <code>checkMemberAccess(this, Member.DECLARED)</code>
325    * as well as <code>checkPackageAccess</code> both having to succeed.
326    *
327    * @param name the name of the field
328    * @return the field
329    * @throws NoSuchFieldException if the field does not exist
330    * @throws SecurityException if the security check fails
331    * @see #getDeclaredFields()
332    * @since 1.1
333    */
334   public native Field getDeclaredField(String fieldName)
335     throws NoSuchFieldException;
336
337   /**
338    * Get all the declared fields in this class, but not those inherited from
339    * superclasses. This returns an array of length 0 if there are no fields,
340    * including for primitive types. This does not return the implicit length
341    * field of arrays. A security check may be performed, with
342    * <code>checkMemberAccess(this, Member.DECLARED)</code> as well as
343    * <code>checkPackageAccess</code> both having to succeed.
344    *
345    * @return all declared fields in this class
346    * @throws SecurityException if the security check fails
347    * @since 1.1
348    */
349   public Field[] getDeclaredFields()
350   {
351     memberAccessCheck(Member.DECLARED);
352     return getDeclaredFields(false);
353   }
354
355   native Field[] getDeclaredFields (boolean publicOnly);
356
357   private native Method _getDeclaredMethod(String methodName, Class[] args);
358
359   /**
360    * Get a method declared in this class, where name is its simple name. The
361    * implicit methods of Object are not available from arrays or interfaces.
362    * Constructors (named "&lt;init&gt;" in the class file) and class initializers
363    * (name "&lt;clinit&gt;") are not available.  The Virtual Machine allows
364    * multiple methods with the same signature but differing return types; in
365    * such a case the most specific return types are favored, then the final
366    * choice is arbitrary. If the method takes no argument, an array of zero
367    * elements and null are equivalent for the types argument. A security
368    * check may be performed, with
369    * <code>checkMemberAccess(this, Member.DECLARED)</code> as well as
370    * <code>checkPackageAccess</code> both having to succeed.
371    *
372    * @param methodName the name of the method
373    * @param types the type of each parameter
374    * @return the method
375    * @throws NoSuchMethodException if the method does not exist
376    * @throws SecurityException if the security check fails
377    * @see #getDeclaredMethods()
378    * @since 1.1
379    */
380   public Method getDeclaredMethod(String methodName, Class<?>... args)
381     throws NoSuchMethodException
382   {
383     memberAccessCheck(Member.DECLARED);
384
385     if ("<init>".equals(methodName) || "<clinit>".equals(methodName))
386       throw new NoSuchMethodException(methodName);
387
388     Method match = _getDeclaredMethod(methodName, args);
389     if (match == null)
390       throw new NoSuchMethodException(methodName);
391     return match;
392   }
393
394   /**
395    * Get all the declared methods in this class, but not those inherited from
396    * superclasses. This returns an array of length 0 if there are no methods,
397    * including for primitive types. This does include the implicit methods of
398    * arrays and interfaces which mirror methods of Object, nor does it
399    * include constructors or the class initialization methods. The Virtual
400    * Machine allows multiple methods with the same signature but differing
401    * return types; all such methods are in the returned array. A security
402    * check may be performed, with
403    * <code>checkMemberAccess(this, Member.DECLARED)</code> as well as
404    * <code>checkPackageAccess</code> both having to succeed.
405    *
406    * @return all declared methods in this class
407    * @throws SecurityException if the security check fails
408    * @since 1.1
409    */
410   public native Method[] getDeclaredMethods();
411  
412   /**
413    * If this is a nested or inner class, return the class that declared it.
414    * If not, return null.
415    *
416    * @return the declaring class of this class
417    * @since 1.1
418    */
419   // This is marked as unimplemented in the JCL book.
420   public native Class<?> getDeclaringClass ();
421
422   private native Field getField (String fieldName, int hash)
423     throws NoSuchFieldException;
424
425   /**
426    * Get a public field declared or inherited in this class, where name is
427    * its simple name. If the class contains multiple accessible fields by
428    * that name, an arbitrary one is returned. The implicit length field of
429    * arrays is not available. A security check may be performed, with
430    * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
431    * <code>checkPackageAccess</code> both having to succeed.
432    *
433    * @param fieldName the name of the field
434    * @return the field
435    * @throws NoSuchFieldException if the field does not exist
436    * @throws SecurityException if the security check fails
437    * @see #getFields()
438    * @since 1.1
439    */
440   public Field getField(String fieldName)
441     throws NoSuchFieldException
442   {
443     memberAccessCheck(Member.PUBLIC);
444     Field field = getField(fieldName, fieldName.hashCode());
445     if (field == null)
446       throw new NoSuchFieldException(fieldName);
447     return field;
448   }
449
450   /**
451    * Get all the public fields declared in this class or inherited from
452    * superclasses. This returns an array of length 0 if there are no fields,
453    * including for primitive types. This does not return the implicit length
454    * field of arrays. A security check may be performed, with
455    * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
456    * <code>checkPackageAccess</code> both having to succeed.
457    *
458    * @return all public fields in this class
459    * @throws SecurityException if the security check fails
460    * @since 1.1
461    */
462   public Field[] getFields()
463   {
464     memberAccessCheck(Member.PUBLIC);
465     return internalGetFields();
466   }
467
468   /**
469    * Like <code>getFields()</code> but without the security checks.
470    */
471   private Field[] internalGetFields()
472   {
473     HashSet set = new HashSet();
474     set.addAll(Arrays.asList(getDeclaredFields(true)));
475     Class[] interfaces = getInterfaces();
476     for (int i = 0; i < interfaces.length; i++)
477       set.addAll(Arrays.asList(interfaces[i].internalGetFields()));
478     Class superClass = getSuperclass();
479     if (superClass != null)
480       set.addAll(Arrays.asList(superClass.internalGetFields()));
481     return (Field[])set.toArray(new Field[set.size()]);
482   }
483
484   /**
485    * Returns the <code>Package</code> in which this class is defined
486    * Returns null when this information is not available from the
487    * classloader of this class.
488    *
489    * @return the package for this class, if it is available
490    * @since 1.2
491    */
492   public Package getPackage()
493   {
494     ClassLoader cl = getClassLoaderInternal();
495     if (cl != null)
496       return cl.getPackage(getPackagePortion(getName()));
497     else
498       return VMClassLoader.getPackage(getPackagePortion(getName()));
499   }
500
501   /**
502    * Get the interfaces this class <em>directly</em> implements, in the
503    * order that they were declared. This returns an empty array, not null,
504    * for Object, primitives, void, and classes or interfaces with no direct
505    * superinterface. Array types return Cloneable and Serializable.
506    *
507    * @return the interfaces this class directly implements
508    */
509   public native Class<?>[] getInterfaces ();
510
511   private final native void getSignature(StringBuffer buffer);
512   private static final native String getSignature(Class[] args,
513                                                   boolean is_construtor);
514
515   public native Method _getMethod(String methodName, Class[] args);
516
517   /**
518    * Get a public method declared or inherited in this class, where name is
519    * its simple name. The implicit methods of Object are not available from
520    * interfaces.  Constructors (named "&lt;init&gt;" in the class file) and class
521    * initializers (name "&lt;clinit&gt;") are not available.  The Virtual
522    * Machine allows multiple methods with the same signature but differing
523    * return types, and the class can inherit multiple methods of the same
524    * return type; in such a case the most specific return types are favored,
525    * then the final choice is arbitrary. If the method takes no argument, an
526    * array of zero elements and null are equivalent for the types argument.
527    * A security check may be performed, with
528    * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
529    * <code>checkPackageAccess</code> both having to succeed.
530    *
531    * @param methodName the name of the method
532    * @param types the type of each parameter
533    * @return the method
534    * @throws NoSuchMethodException if the method does not exist
535    * @throws SecurityException if the security check fails
536    * @see #getMethods()
537    * @since 1.1
538    */
539   public Method getMethod(String methodName, Class<?>... args)
540     throws NoSuchMethodException
541   {
542     memberAccessCheck(Member.PUBLIC);
543
544     if ("<init>".equals(methodName) || "<clinit>".equals(methodName))
545       throw new NoSuchMethodException(methodName);
546
547     Method method = _getMethod(methodName, args);
548     if (method == null)
549       throw new NoSuchMethodException(methodName);
550     return method;
551   }
552
553   private native int _getMethods (Method[] result, int offset);
554   
555   /**
556    * Get all the public methods declared in this class or inherited from
557    * superclasses. This returns an array of length 0 if there are no methods,
558    * including for primitive types. This does not include the implicit
559    * methods of interfaces which mirror methods of Object, nor does it
560    * include constructors or the class initialization methods. The Virtual
561    * Machine allows multiple methods with the same signature but differing
562    * return types; all such methods are in the returned array. A security
563    * check may be performed, with
564    * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
565    * <code>checkPackageAccess</code> both having to succeed.
566    *
567    * @return all public methods in this class
568    * @throws SecurityException if the security check fails
569    * @since 1.1
570    */
571   public native Method[] getMethods();
572
573   /**
574    * Get the modifiers of this class.  These can be decoded using Modifier,
575    * and is limited to one of public, protected, or private, and any of
576    * final, static, abstract, or interface. An array class has the same
577    * public, protected, or private modifier as its component type, and is
578    * marked final but not an interface. Primitive types and void are marked
579    * public and final, but not an interface.
580    *
581    * @return the modifiers of this class
582    * @see Modifer
583    * @since 1.1
584    */
585   public native int getModifiers ();
586   
587   /**
588    * Get the name of this class, separated by dots for package separators.
589    * If the class represents a primitive type, or void, then the
590    * name of the type as it appears in the Java programming language
591    * is returned.  For instance, <code>Byte.TYPE.getName()</code>
592    * returns "byte".
593    *
594    * Arrays are specially encoded as shown on this table.
595    * <pre>
596    * array type          [<em>element type</em>
597    *                     (note that the element type is encoded per
598    *                      this table)
599    * boolean             Z
600    * byte                B
601    * char                C
602    * short               S
603    * int                 I
604    * long                J
605    * float               F
606    * double              D
607    * void                V
608    * class or interface, alone: &lt;dotted name&gt;
609    * class or interface, as element type: L&lt;dotted name&gt;;
610    * </pre>
611    *
612    * @return the name of this class
613    */
614   public native String getName ();
615
616   /**
617    * Get a resource URL using this class's package using the
618    * getClassLoader().getResource() method.  If this class was loaded using
619    * the system classloader, ClassLoader.getSystemResource() is used instead.
620    *
621    * <p>If the name you supply is absolute (it starts with a <code>/</code>),
622    * then the leading <code>/</code> is removed and it is passed on to
623    * getResource(). If it is relative, the package name is prepended, and
624    * <code>.</code>'s are replaced with <code>/</code>.
625    *
626    * <p>The URL returned is system- and classloader-dependent, and could
627    * change across implementations.
628    *
629    * @param resourceName the name of the resource, generally a path
630    * @return the URL to the resource
631    * @throws NullPointerException if name is null
632    * @since 1.1
633    */
634   public URL getResource(String resourceName)
635   {
636     String name = resourcePath(resourceName);
637     ClassLoader loader = getClassLoaderInternal();
638     if (loader == null)
639       return ClassLoader.getSystemResource(name);
640     return loader.getResource(name);
641   }
642
643   /**
644    * Get a resource using this class's package using the
645    * getClassLoader().getResourceAsStream() method.  If this class was loaded
646    * using the system classloader, ClassLoader.getSystemResource() is used
647    * instead.
648    *
649    * <p>If the name you supply is absolute (it starts with a <code>/</code>),
650    * then the leading <code>/</code> is removed and it is passed on to
651    * getResource(). If it is relative, the package name is prepended, and
652    * <code>.</code>'s are replaced with <code>/</code>.
653    *
654    * <p>The URL returned is system- and classloader-dependent, and could
655    * change across implementations.
656    *
657    * @param resourceName the name of the resource, generally a path
658    * @return an InputStream with the contents of the resource in it, or null
659    * @throws NullPointerException if name is null
660    * @since 1.1
661    */
662   public InputStream getResourceAsStream(String resourceName)
663   {
664     String name = resourcePath(resourceName);
665     ClassLoader loader = getClassLoaderInternal();
666     if (loader == null)
667       return ClassLoader.getSystemResourceAsStream(name);
668     return loader.getResourceAsStream(name);
669   }
670
671   private String resourcePath(String resourceName)
672   {
673     if (resourceName.length() > 0)
674       {
675         if (resourceName.charAt(0) != '/')
676           {
677             String pkg = getPackagePortion(getName());
678             if (pkg.length() > 0)
679               resourceName = pkg.replace('.','/') + '/' + resourceName;
680           }
681         else
682           {
683             resourceName = resourceName.substring(1);
684           }
685       }
686     return resourceName;
687   }
688
689   /**
690    * Get the signers of this class. This returns null if there are no signers,
691    * such as for primitive types or void.
692    *
693    * @return the signers of this class
694    * @since 1.1
695    */
696   public native Object[] getSigners ();
697   
698   /**
699    * Set the signers of this class.
700    *
701    * @param signers the signers of this class
702    */
703   native void setSigners(Object[] signers);
704
705   /**
706    * Get the direct superclass of this class.  If this is an interface,
707    * Object, a primitive type, or void, it will return null. If this is an
708    * array type, it will return Object.
709    *
710    * @return the direct superclass of this class
711    */
712   public native Class<? super T> getSuperclass ();
713   
714   /**
715    * Return whether this class is an array type.
716    *
717    * @return whether this class is an array type
718    * @since 1.1
719    */
720   public native boolean isArray ();
721   
722   /**
723    * Discover whether an instance of the Class parameter would be an
724    * instance of this Class as well.  Think of doing
725    * <code>isInstance(c.newInstance())</code> or even
726    * <code>c.newInstance() instanceof (this class)</code>. While this
727    * checks widening conversions for objects, it must be exact for primitive
728    * types.
729    *
730    * @param c the class to check
731    * @return whether an instance of c would be an instance of this class
732    *         as well
733    * @throws NullPointerException if c is null
734    * @since 1.1
735    */
736   public native boolean isAssignableFrom (Class<?> c);
737  
738   /**
739    * Discover whether an Object is an instance of this Class.  Think of it
740    * as almost like <code>o instanceof (this class)</code>.
741    *
742    * @param o the Object to check
743    * @return whether o is an instance of this class
744    * @since 1.1
745    */
746   public native boolean isInstance (Object o);
747   
748   /**
749    * Check whether this class is an interface or not.  Array types are not
750    * interfaces.
751    *
752    * @return whether this class is an interface or not
753    */
754   public native boolean isInterface ();
755   
756   /**
757    * Return whether this class is a primitive type.  A primitive type class
758    * is a class representing a kind of "placeholder" for the various
759    * primitive types, or void.  You can access the various primitive type
760    * classes through java.lang.Boolean.TYPE, java.lang.Integer.TYPE, etc.,
761    * or through boolean.class, int.class, etc.
762    *
763    * @return whether this class is a primitive type
764    * @see Boolean#TYPE
765    * @see Byte#TYPE
766    * @see Character#TYPE
767    * @see Short#TYPE
768    * @see Integer#TYPE
769    * @see Long#TYPE
770    * @see Float#TYPE
771    * @see Double#TYPE
772    * @see Void#TYPE
773    * @since 1.1
774    */
775   public native boolean isPrimitive ();
776   
777   /**
778    * Get a new instance of this class by calling the no-argument constructor.
779    * The class is initialized if it has not been already. A security check
780    * may be performed, with <code>checkMemberAccess(this, Member.PUBLIC)</code>
781    * as well as <code>checkPackageAccess</code> both having to succeed.
782    *
783    * @return a new instance of this class
784    * @throws InstantiationException if there is not a no-arg constructor
785    *         for this class, including interfaces, abstract classes, arrays,
786    *         primitive types, and void; or if an exception occurred during
787    *         the constructor
788    * @throws IllegalAccessException if you are not allowed to access the
789    *         no-arg constructor because of scoping reasons
790    * @throws SecurityException if the security check fails
791    * @throws ExceptionInInitializerError if class initialization caused by
792    *         this call fails with an exception
793    */
794   public native T newInstance ()
795     throws InstantiationException, IllegalAccessException;
796
797   // We need a native method to retrieve the protection domain, because we
798   // can't add fields to java.lang.Class that are accessible from Java.
799   private native ProtectionDomain getProtectionDomain0();
800
801   /**
802    * Returns the protection domain of this class. If the classloader did not
803    * record the protection domain when creating this class the unknown
804    * protection domain is returned which has a <code>null</code> code source
805    * and all permissions. A security check may be performed, with
806    * <code>RuntimePermission("getProtectionDomain")</code>.
807    *
808    * @return the protection domain
809    * @throws SecurityException if the security manager exists and the caller
810    * does not have <code>RuntimePermission("getProtectionDomain")</code>.
811    * @see RuntimePermission
812    * @since 1.2
813    */
814   public ProtectionDomain getProtectionDomain()
815   {
816     SecurityManager sm = System.getSecurityManager();
817     if (sm != null)
818       sm.checkPermission(VMClassLoader.protectionDomainPermission);
819     
820     ProtectionDomain protectionDomain = getProtectionDomain0();
821
822     if (protectionDomain == null)
823       return VMClassLoader.unknownProtectionDomain;
824     else
825       return protectionDomain;
826   }
827
828   /**
829    * Return the human-readable form of this Object.  For an object, this
830    * is either "interface " or "class " followed by <code>getName()</code>,
831    * for primitive types and void it is just <code>getName()</code>.
832    *
833    * @return the human-readable form of this Object
834    */
835   public String toString()
836   {
837     if (isPrimitive())
838       return getName();
839     return (isInterface() ? "interface " : "class ") + getName();
840   }
841
842   /**
843    * Returns the desired assertion status of this class, if it were to be
844    * initialized at this moment. The class assertion status, if set, is
845    * returned; the backup is the default package status; then if there is
846    * a class loader, that default is returned; and finally the system default
847    * is returned. This method seldom needs calling in user code, but exists
848    * for compilers to implement the assert statement. Note that there is no
849    * guarantee that the result of this method matches the class's actual
850    * assertion status.
851    *
852    * @return the desired assertion status
853    * @see ClassLoader#setClassAssertionStatus(String, boolean)
854    * @see ClassLoader#setPackageAssertionStatus(String, boolean)
855    * @see ClassLoader#setDefaultAssertionStatus(boolean)
856    * @since 1.4
857    */
858   public boolean desiredAssertionStatus()
859   {
860     ClassLoader c = getClassLoaderInternal();
861     Object status;
862     if (c == null)
863       return VMClassLoader.defaultAssertionStatus();
864     if (c.classAssertionStatus != null)
865       synchronized (c)
866         {
867           status = c.classAssertionStatus.get(getName());
868           if (status != null)
869             return status.equals(Boolean.TRUE);
870         }
871     else
872       {
873         status = ClassLoader.systemClassAssertionStatus.get(getName());
874         if (status != null)
875           return status.equals(Boolean.TRUE);
876       }
877     if (c.packageAssertionStatus != null)
878       synchronized (c)
879         {
880           String name = getPackagePortion(getName());
881           if ("".equals(name))
882             status = c.packageAssertionStatus.get(null);
883           else
884             do
885               {
886                 status = c.packageAssertionStatus.get(name);
887                 name = getPackagePortion(name);
888               }
889             while (! "".equals(name) && status == null);
890           if (status != null)
891             return status.equals(Boolean.TRUE);
892         }
893     else
894       {
895         String name = getPackagePortion(getName());
896         if ("".equals(name))
897           status = ClassLoader.systemPackageAssertionStatus.get(null);
898         else
899           do
900             {
901               status = ClassLoader.systemPackageAssertionStatus.get(name);
902               name = getPackagePortion(name);
903             }
904           while (! "".equals(name) && status == null);
905         if (status != null)
906           return status.equals(Boolean.TRUE);
907       }
908     return c.defaultAssertionStatus;
909   }
910
911   /**
912    * Strip the last portion of the name (after the last dot).
913    *
914    * @param name the name to get package of
915    * @return the package name, or "" if no package
916    */
917   private static String getPackagePortion(String name)
918   {
919     int lastInd = name.lastIndexOf('.');
920     if (lastInd == -1)
921       return "";
922     return name.substring(0, lastInd);
923   }
924
925   /**
926    * Perform security checks common to all of the methods that
927    * get members of this Class.
928    */
929   private void memberAccessCheck(int which)
930   {
931     SecurityManager sm = System.getSecurityManager();
932     if (sm != null)
933       {
934         sm.checkMemberAccess(this, which);
935         Package pkg = getPackage();
936         if (pkg != null)
937           sm.checkPackageAccess(pkg.getName());
938       }
939   }
940
941
942   /**
943    * <p>
944    * Casts this class to represent a subclass of the specified class.
945    * This method is useful for `narrowing' the type of a class so that
946    * the class object, and instances of that class, can match the contract
947    * of a more restrictive method.  For example, if this class has the
948    * static type of <code>Class&lt;Object&gt;</code>, and a dynamic type of
949    * <code>Class&lt;Rectangle&gt;</code>, then, assuming <code>Shape</code> is
950    * a superclass of <code>Rectangle</code>, this method can be used on
951    * this class with the parameter, <code>Class&lt;Shape&gt;</code>, to retain
952    * the same instance but with the type
953    * <code>Class&lt;? extends Shape&gt;</code>.
954    * </p>
955    * <p>
956    * If this class can be converted to an instance which is parameterised
957    * over a subtype of the supplied type, <code>U</code>, then this method
958    * returns an appropriately cast reference to this object.  Otherwise,
959    * a <code>ClassCastException</code> is thrown.
960    * </p>
961    * 
962    * @param klass the class object, the parameterized type (<code>U</code>) of
963    *              which should be a superclass of the parameterized type of
964    *              this instance.
965    * @return a reference to this object, appropriately cast.
966    * @throws ClassCastException if this class can not be converted to one
967    *                            which represents a subclass of the specified
968    *                            type, <code>U</code>. 
969    * @since 1.5
970    */
971   public <U> Class<? extends U> asSubclass(Class<U> klass)
972   {
973     if (! klass.isAssignableFrom(this))
974       throw new ClassCastException();
975     return (Class<? extends U>) this;
976   }
977
978   /**
979    * Returns the specified object, cast to this <code>Class</code>' type.
980    *
981    * @param obj the object to cast
982    * @throws ClassCastException  if obj is not an instance of this class
983    * @since 1.5
984    */
985   public T cast(Object obj)
986   {
987     if (obj != null && ! isInstance(obj))
988       throw new ClassCastException();
989     return (T) obj;
990   }
991
992   /**
993    * Returns the enumeration constants of this class, or
994    * null if this class is not an <code>Enum</code>.
995    *
996    * @return an array of <code>Enum</code> constants
997    *         associated with this class, or null if this
998    *         class is not an <code>enum</code>.
999    * @since 1.5
1000    */
1001   public T[] getEnumConstants()
1002   {
1003     if (isEnum())
1004       {
1005         try
1006           {
1007             return (T[]) getMethod("values").invoke(null);
1008           }
1009         catch (NoSuchMethodException exception)
1010           {
1011             throw new Error("Enum lacks values() method");
1012           }
1013         catch (IllegalAccessException exception)
1014           {
1015             throw new Error("Unable to access Enum class");
1016           }
1017         catch (InvocationTargetException exception)
1018           {
1019             throw new
1020               RuntimeException("The values method threw an exception",
1021                                exception);
1022           }
1023       }
1024     else
1025       {
1026         return null;
1027       }
1028   }
1029
1030   /**
1031    * Returns true if this class is an <code>Enum</code>.
1032    *
1033    * @return true if this is an enumeration class.
1034    * @since 1.5
1035    */
1036   public native boolean isEnum();
1037
1038
1039   /**
1040    * Returns true if this class is a synthetic class, generated by
1041    * the compiler.
1042    *
1043    * @return true if this is a synthetic class.
1044    * @since 1.5
1045    */
1046   public native boolean isSynthetic();
1047
1048
1049   /**
1050    * Returns true if this class is an <code>Annotation</code>.
1051    *
1052    * @return true if this is an annotation class.
1053    * @since 1.5
1054    */
1055   public native boolean isAnnotation();
1056
1057
1058   /**
1059    * Returns the simple name for this class, as used in the source
1060    * code.  For normal classes, this is the content returned by
1061    * <code>getName()</code> which follows the last ".".  Anonymous
1062    * classes have no name, and so the result of calling this method is
1063    * "".  The simple name of an array consists of the simple name of
1064    * its component type, followed by "[]".  Thus, an array with the
1065    * component type of an anonymous class has a simple name of simply
1066    * "[]".
1067    *
1068    * @return the simple name for this class.
1069    * @since 1.5
1070    */
1071   public String getSimpleName()
1072   {
1073     StringBuffer sb = new StringBuffer();
1074     Class klass = this;
1075     int arrayCount = 0;
1076     while (klass.isArray())
1077       {
1078         klass = klass.getComponentType();
1079         ++arrayCount;
1080       }
1081     if (! klass.isAnonymousClass())
1082       {
1083         String fullName = klass.getName();
1084         sb.append(fullName, fullName.lastIndexOf(".") + 1, fullName.length());
1085       }
1086     while (arrayCount-- > 0)
1087       sb.append("[]");
1088     return sb.toString();
1089   }
1090
1091   /**
1092    * Returns the class which immediately encloses this class.  If this class
1093    * is a top-level class, this method returns <code>null</code>.
1094    *
1095    * @return the immediate enclosing class, or <code>null</code> if this is
1096    *         a top-level class.
1097    * @since 1.5
1098    */
1099   public native Class<?> getEnclosingClass();
1100
1101   /**
1102    * Returns the constructor which immediately encloses this class.  If
1103    * this class is a top-level class, or a local or anonymous class
1104    * immediately enclosed by a type definition, instance initializer
1105    * or static initializer, then <code>null</code> is returned.
1106    *
1107    * @return the immediate enclosing constructor if this class is
1108    *         declared within a constructor.  Otherwise, <code>null</code>
1109    *         is returned.
1110    * @since 1.5
1111    */
1112   public native Constructor<T> getEnclosingConstructor();
1113
1114   /**
1115    * Returns the method which immediately encloses this class.  If
1116    * this class is a top-level class, or a local or anonymous class
1117    * immediately enclosed by a type definition, instance initializer
1118    * or static initializer, then <code>null</code> is returned.
1119    *
1120    * @return the immediate enclosing method if this class is
1121    *         declared within a method.  Otherwise, <code>null</code>
1122    *         is returned.
1123    * @since 1.5
1124    */
1125   public native Method getEnclosingMethod();
1126
1127   private native String getClassSignature();
1128
1129   /**
1130    * <p>
1131    * Returns an array of <code>Type</code> objects which represent the
1132    * interfaces directly implemented by this class or extended by this
1133    * interface.
1134    * </p>
1135    * <p>
1136    * If one of the superinterfaces is a parameterized type, then the
1137    * object returned for this interface reflects the actual type
1138    * parameters used in the source code.  Type parameters are created
1139    * using the semantics specified by the <code>ParameterizedType</code>
1140    * interface, and only if an instance has not already been created.
1141    * </p>
1142    * <p>
1143    * The order of the interfaces in the array matches the order in which
1144    * the interfaces are declared.  For classes which represent an array,
1145    * an array of two interfaces, <code>Cloneable</code> and
1146    * <code>Serializable</code>, is always returned, with the objects in
1147    * that order.  A class representing a primitive type or void always
1148    * returns an array of zero size.
1149    * </p>
1150    *
1151    * @return an array of interfaces implemented or extended by this class.
1152    * @throws GenericSignatureFormatError if the generic signature of one
1153    *         of the interfaces does not comply with that specified by the Java
1154    *         Virtual Machine specification, 3rd edition.
1155    * @throws TypeNotPresentException if any of the superinterfaces refers
1156    *         to a non-existant type.
1157    * @throws MalformedParameterizedTypeException if any of the interfaces
1158    *         refer to a parameterized type that can not be instantiated for
1159    *         some reason.
1160    * @since 1.5
1161    * @see java.lang.reflect.ParameterizedType
1162    */
1163   public Type[] getGenericInterfaces()
1164   {
1165     if (isPrimitive())
1166       return new Type[0];
1167
1168     String sig = getClassSignature();
1169     if (sig == null)
1170       return getInterfaces();
1171
1172     ClassSignatureParser p = new ClassSignatureParser(this, sig);
1173     return p.getInterfaceTypes();
1174   }
1175
1176   /**
1177    * <p>
1178    * Returns a <code>Type</code> object representing the direct superclass,
1179    * whether class, interface, primitive type or void, of this class.
1180    * If this class is an array class, then a class instance representing
1181    * the <code>Object</code> class is returned.  If this class is primitive,
1182    * an interface, or a representation of either the <code>Object</code>
1183    * class or void, then <code>null</code> is returned.
1184    * </p>
1185    * <p>
1186    * If the superclass is a parameterized type, then the
1187    * object returned for this interface reflects the actual type
1188    * parameters used in the source code.  Type parameters are created
1189    * using the semantics specified by the <code>ParameterizedType</code>
1190    * interface, and only if an instance has not already been created.
1191    * </p>
1192    *
1193    * @return the superclass of this class.
1194    * @throws GenericSignatureFormatError if the generic signature of the
1195    *         class does not comply with that specified by the Java
1196    *         Virtual Machine specification, 3rd edition.
1197    * @throws TypeNotPresentException if the superclass refers
1198    *         to a non-existant type.
1199    * @throws MalformedParameterizedTypeException if the superclass
1200    *         refers to a parameterized type that can not be instantiated for
1201    *         some reason.
1202    * @since 1.5
1203    * @see java.lang.reflect.ParameterizedType
1204    */
1205   public Type getGenericSuperclass()
1206   {
1207     if (isArray())
1208       return Object.class;
1209
1210     if (isPrimitive() || isInterface() || this == Object.class)
1211       return null;
1212
1213     String sig = getClassSignature();
1214     if (sig == null)
1215       return getSuperclass();
1216
1217     ClassSignatureParser p = new ClassSignatureParser(this, sig);
1218     return p.getSuperclassType();
1219   }
1220
1221   /**
1222    * Returns an array of <code>TypeVariable</code> objects that represents
1223    * the type variables declared by this class, in declaration order.
1224    * An array of size zero is returned if this class has no type
1225    * variables.
1226    *
1227    * @return the type variables associated with this class. 
1228    * @throws GenericSignatureFormatError if the generic signature does
1229    *         not conform to the format specified in the Virtual Machine
1230    *         specification, version 3.
1231    * @since 1.5
1232    */
1233   public TypeVariable<Class<T>>[] getTypeParameters()
1234   {
1235     String sig = getClassSignature();
1236     if (sig == null)
1237       return (TypeVariable<Class<T>>[])new TypeVariable[0];
1238
1239     ClassSignatureParser p = new ClassSignatureParser(this, sig);
1240     return p.getTypeParameters();
1241   }
1242
1243   /**
1244    * Returns this class' annotation for the specified annotation type,
1245    * or <code>null</code> if no such annotation exists.
1246    *
1247    * @param annotationClass the type of annotation to look for.
1248    * @return this class' annotation for the specified type, or
1249    *         <code>null</code> if no such annotation exists.
1250    * @since 1.5
1251    */
1252   public <A extends Annotation> A getAnnotation(Class<A> annotationClass)
1253   {
1254     A foundAnnotation = null;
1255     Annotation[] annotations = getAnnotations();
1256     for (Annotation annotation : annotations)
1257       if (annotation.annotationType() == annotationClass)
1258         foundAnnotation = (A) annotation;
1259     return foundAnnotation;
1260   }
1261
1262   /**
1263    * Returns all annotations associated with this class.  If there are
1264    * no annotations associated with this class, then a zero-length array
1265    * will be returned.  The returned array may be modified by the client
1266    * code, but this will have no effect on the annotation content of this
1267    * class, and hence no effect on the return value of this method for
1268    * future callers.
1269    *
1270    * @return this class' annotations.
1271    * @since 1.5
1272    */
1273   public Annotation[] getAnnotations()
1274   {
1275     HashMap<Class, Annotation> map = new HashMap<Class, Annotation>();
1276     for (Annotation a : getDeclaredAnnotations())
1277       map.put((Class) a.annotationType(), a);
1278     for (Class<? super T> s = getSuperclass();
1279          s != null;
1280          s = s.getSuperclass())
1281       {
1282         for (Annotation a : s.getDeclaredAnnotations())
1283           {
1284             Class k = (Class) a.annotationType();
1285             if (! map.containsKey(k) && k.isAnnotationPresent(Inherited.class))
1286               map.put(k, a);
1287           }
1288       }
1289     Collection<Annotation> v = map.values();
1290     return v.toArray(new Annotation[v.size()]);
1291   }
1292
1293   /**
1294    * Returns all annotations directly defined by this class.  If there are
1295    * no annotations associated with this class, then a zero-length array
1296    * will be returned.  The returned array may be modified by the client
1297    * code, but this will have no effect on the annotation content of this
1298    * class, and hence no effect on the return value of this method for
1299    * future callers.
1300    *
1301    * @return the annotations directly defined by this class.
1302    * @since 1.5
1303    */
1304   public Annotation[] getDeclaredAnnotations()
1305   {
1306     Annotation[] result = getDeclaredAnnotationsInternal();
1307     if (result == null)
1308       result = new Annotation[0];
1309     return result;
1310   }
1311
1312   private native Annotation[] getDeclaredAnnotationsInternal();
1313
1314   /**
1315    * Returns true if an annotation for the specified type is associated
1316    * with this class.  This is primarily a short-hand for using marker
1317    * annotations.
1318    *
1319    * @param annotationClass the type of annotation to look for.
1320    * @return true if an annotation exists for the specified type.
1321    * @since 1.5
1322    */
1323   public boolean isAnnotationPresent(Class<? extends Annotation> 
1324                                      annotationClass)
1325   {
1326     return getAnnotation(annotationClass) != null;
1327   }
1328
1329   /**
1330    * Returns true if this object represents an anonymous class.
1331    *
1332    * @return true if this object represents an anonymous class.
1333    * @since 1.5
1334    */
1335   public native boolean isAnonymousClass();
1336
1337   /**
1338    * Returns true if this object represents an local class.
1339    *
1340    * @return true if this object represents an local class.
1341    * @since 1.5
1342    */
1343   public native boolean isLocalClass();
1344
1345   /**
1346    * Returns true if this object represents an member class.
1347    *
1348    * @return true if this object represents an member class.
1349    * @since 1.5
1350    */
1351   public native boolean isMemberClass();
1352 }