2008-05-30 Vladimir Makarov <vmakarov@redhat.com>
[official-gcc.git] / libjava / java / lang / Class.java
bloba4e8ee5929e5a15e8dbec891d875e49ac2172108
1 /* Class.java -- Representation of a Java class.
2 Copyright (C) 1998, 1999, 2000, 2002, 2003, 2004, 2005, 2006, 2007
3 Free Software Foundation
5 This file is part of GNU Classpath.
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.
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.
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.
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.
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. */
39 package java.lang;
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.AccessController;
55 import java.security.PrivilegedAction;
56 import java.security.ProtectionDomain;
57 import java.util.ArrayList;
58 import java.util.Arrays;
59 import java.util.LinkedHashSet;
60 import java.util.HashMap;
61 import java.util.Collection;
62 import java.lang.reflect.AnnotatedElement;
63 import java.lang.annotation.Annotation;
64 import java.lang.annotation.Inherited;
65 import java.lang.reflect.AccessibleObject;
67 /**
68 * A Class represents a Java type. There will never be multiple Class
69 * objects with identical names and ClassLoaders. Primitive types, array
70 * types, and void also have a Class object.
72 * <p>Arrays with identical type and number of dimensions share the same class.
73 * The array class ClassLoader is the same as the ClassLoader of the element
74 * type of the array (which can be null to indicate the bootstrap classloader).
75 * The name of an array class is <code>[&lt;signature format&gt;;</code>.
76 * <p> For example,
77 * String[]'s class is <code>[Ljava.lang.String;</code>. boolean, byte,
78 * short, char, int, long, float and double have the "type name" of
79 * Z,B,S,C,I,J,F,D for the purposes of array classes. If it's a
80 * multidimensioned array, the same principle applies:
81 * <code>int[][][]</code> == <code>[[[I</code>.
83 * <p>There is no public constructor - Class objects are obtained only through
84 * the virtual machine, as defined in ClassLoaders.
86 * @serialData Class objects serialize specially:
87 * <code>TC_CLASS ClassDescriptor</code>. For more serialization information,
88 * see {@link ObjectStreamClass}.
90 * @author John Keiser
91 * @author Eric Blake (ebb9@email.byu.edu)
92 * @author Tom Tromey (tromey@cygnus.com)
93 * @since 1.0
94 * @see ClassLoader
96 public final class Class<T>
97 implements Type, AnnotatedElement, GenericDeclaration, Serializable
99 /**
100 * Class is non-instantiable from Java code; only the VM can create
101 * instances of this class.
103 private Class ()
107 // Initialize the class.
108 private native void initializeClass ();
110 // finalization
111 protected native void finalize () throws Throwable;
114 * Use the classloader of the current class to load, link, and initialize
115 * a class. This is equivalent to your code calling
116 * <code>Class.forName(name, true, getClass().getClassLoader())</code>.
118 * @param name the name of the class to find
119 * @return the Class object representing the class
120 * @throws ClassNotFoundException if the class was not found by the
121 * classloader
122 * @throws LinkageError if linking the class fails
123 * @throws ExceptionInInitializerError if the class loads, but an exception
124 * occurs during initialization
126 public static native Class<?> forName (String className)
127 throws ClassNotFoundException;
129 // A private internal method that is called by compiler-generated code.
130 private static Class forName (String className, Class caller)
131 throws ClassNotFoundException
133 return forName(className, true, caller.getClassLoaderInternal());
138 * Use the specified classloader to load and link a class. If the loader
139 * is null, this uses the bootstrap class loader (provide the security
140 * check succeeds). Unfortunately, this method cannot be used to obtain
141 * the Class objects for primitive types or for void, you have to use
142 * the fields in the appropriate java.lang wrapper classes.
144 * <p>Calls <code>classloader.loadclass(name, initialize)</code>.
146 * @param name the name of the class to find
147 * @param initialize whether or not to initialize the class at this time
148 * @param classloader the classloader to use to find the class; null means
149 * to use the bootstrap class loader
150 * @throws ClassNotFoundException if the class was not found by the
151 * classloader
152 * @throws LinkageError if linking the class fails
153 * @throws ExceptionInInitializerError if the class loads, but an exception
154 * occurs during initialization
155 * @throws SecurityException if the <code>classloader</code> argument
156 * is <code>null</code> and the caller does not have the
157 * <code>RuntimePermission("getClassLoader")</code> permission
158 * @see ClassLoader
159 * @since 1.2
161 public static native Class<?> forName (String className, boolean initialize,
162 ClassLoader loader)
163 throws ClassNotFoundException;
166 * Get all the public member classes and interfaces declared in this
167 * class or inherited from superclasses. This returns an array of length
168 * 0 if there are no member classes, including for primitive types. A
169 * security check may be performed, with
170 * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
171 * <code>checkPackageAccess</code> both having to succeed.
173 * @return all public member classes in this class
174 * @throws SecurityException if the security check fails
175 * @since 1.1
177 public Class<?>[] getClasses()
179 memberAccessCheck(Member.PUBLIC);
180 return internalGetClasses();
184 * Like <code>getClasses()</code> but without the security checks.
186 private Class<?>[] internalGetClasses()
188 ArrayList<Class> list = new ArrayList<Class>();
189 list.addAll(Arrays.asList(getDeclaredClasses(true)));
190 Class superClass = getSuperclass();
191 if (superClass != null)
192 list.addAll(Arrays.asList(superClass.internalGetClasses()));
193 return list.toArray(new Class<?>[list.size()]);
197 * Get the ClassLoader that loaded this class. If the class was loaded
198 * by the bootstrap classloader, this method will return null.
199 * If there is a security manager, and the caller's class loader is not
200 * an ancestor of the requested one, a security check of
201 * <code>RuntimePermission("getClassLoader")</code>
202 * must first succeed. Primitive types and void return null.
204 * @return the ClassLoader that loaded this class
205 * @throws SecurityException if the security check fails
206 * @see ClassLoader
207 * @see RuntimePermission
209 public native ClassLoader getClassLoader ();
211 // A private internal method that is called by compiler-generated code.
212 private final native ClassLoader getClassLoader (Class caller);
215 * Internal method that circumvents the usual security checks when
216 * getting the class loader.
218 private native ClassLoader getClassLoaderInternal ();
221 * If this is an array, get the Class representing the type of array.
222 * Examples: "[[Ljava.lang.String;" would return "[Ljava.lang.String;", and
223 * calling getComponentType on that would give "java.lang.String". If
224 * this is not an array, returns null.
226 * @return the array type of this class, or null
227 * @see Array
228 * @since 1.1
230 public native Class<?> getComponentType ();
233 * Get a public constructor declared in this class. If the constructor takes
234 * no argument, an array of zero elements and null are equivalent for the
235 * types argument. A security check may be performed, with
236 * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
237 * <code>checkPackageAccess</code> both having to succeed.
239 * @param types the type of each parameter
240 * @return the constructor
241 * @throws NoSuchMethodException if the constructor does not exist
242 * @throws SecurityException if the security check fails
243 * @see #getConstructors()
244 * @since 1.1
246 public native Constructor<T> getConstructor(Class<?>... args)
247 throws NoSuchMethodException;
250 * Get all the public constructors of this class. This returns an array of
251 * length 0 if there are no constructors, including for primitive types,
252 * arrays, and interfaces. It does, however, include the default
253 * constructor if one was supplied by the compiler. A security check may
254 * be performed, with <code>checkMemberAccess(this, Member.PUBLIC)</code>
255 * as well as <code>checkPackageAccess</code> both having to succeed.
257 * @return all public constructors in this class
258 * @throws SecurityException if the security check fails
259 * @since 1.1
261 public Constructor<?>[] getConstructors()
263 memberAccessCheck(Member.PUBLIC);
264 return getDeclaredConstructors(true);
268 * Get a constructor declared in this class. If the constructor takes no
269 * argument, an array of zero elements and null are equivalent for the
270 * types argument. A security check may be performed, with
271 * <code>checkMemberAccess(this, Member.DECLARED)</code> as well as
272 * <code>checkPackageAccess</code> both having to succeed.
274 * @param types the type of each parameter
275 * @return the constructor
276 * @throws NoSuchMethodException if the constructor does not exist
277 * @throws SecurityException if the security check fails
278 * @see #getDeclaredConstructors()
279 * @since 1.1
281 public native Constructor<T> getDeclaredConstructor(Class<?>... args)
282 throws NoSuchMethodException;
285 * Get all the declared member classes and interfaces in this class, but
286 * not those inherited from superclasses. This returns an array of length
287 * 0 if there are no member classes, including for primitive types. A
288 * security check may be performed, with
289 * <code>checkMemberAccess(this, Member.DECLARED)</code> as well as
290 * <code>checkPackageAccess</code> both having to succeed.
292 * @return all declared member classes in this class
293 * @throws SecurityException if the security check fails
294 * @since 1.1
296 public Class<?>[] getDeclaredClasses()
298 memberAccessCheck(Member.DECLARED);
299 return getDeclaredClasses(false);
302 native Class<?>[] getDeclaredClasses (boolean publicOnly);
305 * Get all the declared constructors of this class. This returns an array of
306 * length 0 if there are no constructors, including for primitive types,
307 * arrays, and interfaces. It does, however, include the default
308 * constructor if one was supplied by the compiler. A security check may
309 * be performed, with <code>checkMemberAccess(this, Member.DECLARED)</code>
310 * as well as <code>checkPackageAccess</code> both having to succeed.
312 * @return all constructors in this class
313 * @throws SecurityException if the security check fails
314 * @since 1.1
316 public Constructor<?>[] getDeclaredConstructors()
318 memberAccessCheck(Member.DECLARED);
319 return getDeclaredConstructors(false);
322 native Constructor<?>[] getDeclaredConstructors (boolean publicOnly);
325 * Get a field declared in this class, where name is its simple name. The
326 * implicit length field of arrays is not available. A security check may
327 * be performed, with <code>checkMemberAccess(this, Member.DECLARED)</code>
328 * as well as <code>checkPackageAccess</code> both having to succeed.
330 * @param name the name of the field
331 * @return the field
332 * @throws NoSuchFieldException if the field does not exist
333 * @throws SecurityException if the security check fails
334 * @see #getDeclaredFields()
335 * @since 1.1
337 public native Field getDeclaredField(String fieldName)
338 throws NoSuchFieldException;
341 * Get all the declared fields in this class, but not those inherited from
342 * superclasses. This returns an array of length 0 if there are no fields,
343 * including for primitive types. This does not return the implicit length
344 * field of arrays. A security check may be performed, with
345 * <code>checkMemberAccess(this, Member.DECLARED)</code> as well as
346 * <code>checkPackageAccess</code> both having to succeed.
348 * @return all declared fields in this class
349 * @throws SecurityException if the security check fails
350 * @since 1.1
352 public Field[] getDeclaredFields()
354 memberAccessCheck(Member.DECLARED);
355 return getDeclaredFields(false);
358 native Field[] getDeclaredFields (boolean publicOnly);
360 private native Method _getDeclaredMethod(String methodName, Class[] args);
363 * Get a method declared in this class, where name is its simple name. The
364 * implicit methods of Object are not available from arrays or interfaces.
365 * Constructors (named "&lt;init&gt;" in the class file) and class initializers
366 * (name "&lt;clinit&gt;") are not available. The Virtual Machine allows
367 * multiple methods with the same signature but differing return types; in
368 * such a case the most specific return types are favored, then the final
369 * choice is arbitrary. If the method takes no argument, an array of zero
370 * elements and null are equivalent for the types argument. A security
371 * check may be performed, with
372 * <code>checkMemberAccess(this, Member.DECLARED)</code> as well as
373 * <code>checkPackageAccess</code> both having to succeed.
375 * @param methodName the name of the method
376 * @param types the type of each parameter
377 * @return the method
378 * @throws NoSuchMethodException if the method does not exist
379 * @throws SecurityException if the security check fails
380 * @see #getDeclaredMethods()
381 * @since 1.1
383 public Method getDeclaredMethod(String methodName, Class<?>... args)
384 throws NoSuchMethodException
386 memberAccessCheck(Member.DECLARED);
388 if ("<init>".equals(methodName) || "<clinit>".equals(methodName))
389 throw new NoSuchMethodException(methodName);
391 Method match = _getDeclaredMethod(methodName, args);
392 if (match == null)
393 throw new NoSuchMethodException(methodName);
394 return match;
398 * Get all the declared methods in this class, but not those inherited from
399 * superclasses. This returns an array of length 0 if there are no methods,
400 * including for primitive types. This does include the implicit methods of
401 * arrays and interfaces which mirror methods of Object, nor does it
402 * include constructors or the class initialization methods. The Virtual
403 * Machine allows multiple methods with the same signature but differing
404 * return types; all such methods are in the returned array. A security
405 * check may be performed, with
406 * <code>checkMemberAccess(this, Member.DECLARED)</code> as well as
407 * <code>checkPackageAccess</code> both having to succeed.
409 * @return all declared methods in this class
410 * @throws SecurityException if the security check fails
411 * @since 1.1
413 public native Method[] getDeclaredMethods();
416 * If this is a nested or inner class, return the class that declared it.
417 * If not, return null.
419 * @return the declaring class of this class
420 * @since 1.1
422 // This is marked as unimplemented in the JCL book.
423 public native Class<?> getDeclaringClass ();
425 private native Field getField (String fieldName, int hash)
426 throws NoSuchFieldException;
429 * Get a public field declared or inherited in this class, where name is
430 * its simple name. If the class contains multiple accessible fields by
431 * that name, an arbitrary one is returned. The implicit length field of
432 * arrays is not available. A security check may be performed, with
433 * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
434 * <code>checkPackageAccess</code> both having to succeed.
436 * @param fieldName the name of the field
437 * @return the field
438 * @throws NoSuchFieldException if the field does not exist
439 * @throws SecurityException if the security check fails
440 * @see #getFields()
441 * @since 1.1
443 public Field getField(String fieldName)
444 throws NoSuchFieldException
446 memberAccessCheck(Member.PUBLIC);
447 Field field = getField(fieldName, fieldName.hashCode());
448 if (field == null)
449 throw new NoSuchFieldException(fieldName);
450 return field;
454 * Get all the public fields declared in this class or inherited from
455 * superclasses. This returns an array of length 0 if there are no fields,
456 * including for primitive types. This does not return the implicit length
457 * field of arrays. A security check may be performed, with
458 * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
459 * <code>checkPackageAccess</code> both having to succeed.
461 * @return all public fields in this class
462 * @throws SecurityException if the security check fails
463 * @since 1.1
465 public Field[] getFields()
467 memberAccessCheck(Member.PUBLIC);
468 return internalGetFields();
472 * Like <code>getFields()</code> but without the security checks.
474 private Field[] internalGetFields()
476 LinkedHashSet set = new LinkedHashSet();
477 set.addAll(Arrays.asList(getDeclaredFields(true)));
478 Class[] interfaces = getInterfaces();
479 for (int i = 0; i < interfaces.length; i++)
480 set.addAll(Arrays.asList(interfaces[i].internalGetFields()));
481 Class superClass = getSuperclass();
482 if (superClass != null)
483 set.addAll(Arrays.asList(superClass.internalGetFields()));
484 return (Field[])set.toArray(new Field[set.size()]);
488 * Returns the <code>Package</code> in which this class is defined
489 * Returns null when this information is not available from the
490 * classloader of this class.
492 * @return the package for this class, if it is available
493 * @since 1.2
495 public Package getPackage()
497 ClassLoader cl = getClassLoaderInternal();
498 if (cl != null)
499 return cl.getPackage(getPackagePortion(getName()));
500 else
501 return VMClassLoader.getPackage(getPackagePortion(getName()));
505 * Get the interfaces this class <em>directly</em> implements, in the
506 * order that they were declared. This returns an empty array, not null,
507 * for Object, primitives, void, and classes or interfaces with no direct
508 * superinterface. Array types return Cloneable and Serializable.
510 * @return the interfaces this class directly implements
512 public native Class<?>[] getInterfaces ();
514 private final native void getSignature(StringBuffer buffer);
515 private static final native String getSignature(Class[] args,
516 boolean is_construtor);
518 public native Method _getMethod(String methodName, Class[] args);
521 * Get a public method declared or inherited in this class, where name is
522 * its simple name. The implicit methods of Object are not available from
523 * interfaces. Constructors (named "&lt;init&gt;" in the class file) and class
524 * initializers (name "&lt;clinit&gt;") are not available. The Virtual
525 * Machine allows multiple methods with the same signature but differing
526 * return types, and the class can inherit multiple methods of the same
527 * return type; in such a case the most specific return types are favored,
528 * then the final choice is arbitrary. If the method takes no argument, an
529 * array of zero elements and null are equivalent for the types argument.
530 * A security check may be performed, with
531 * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
532 * <code>checkPackageAccess</code> both having to succeed.
534 * @param methodName the name of the method
535 * @param types the type of each parameter
536 * @return the method
537 * @throws NoSuchMethodException if the method does not exist
538 * @throws SecurityException if the security check fails
539 * @see #getMethods()
540 * @since 1.1
542 public Method getMethod(String methodName, Class<?>... args)
543 throws NoSuchMethodException
545 memberAccessCheck(Member.PUBLIC);
547 if ("<init>".equals(methodName) || "<clinit>".equals(methodName))
548 throw new NoSuchMethodException(methodName);
550 Method method = _getMethod(methodName, args);
551 if (method == null)
552 throw new NoSuchMethodException(methodName);
553 return method;
556 private native int _getMethods (Method[] result, int offset);
559 * Get all the public methods declared in this class or inherited from
560 * superclasses. This returns an array of length 0 if there are no methods,
561 * including for primitive types. This does not include the implicit
562 * methods of interfaces which mirror methods of Object, nor does it
563 * include constructors or the class initialization methods. The Virtual
564 * Machine allows multiple methods with the same signature but differing
565 * return types; all such methods are in the returned array. A security
566 * check may be performed, with
567 * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
568 * <code>checkPackageAccess</code> both having to succeed.
570 * @return all public methods in this class
571 * @throws SecurityException if the security check fails
572 * @since 1.1
574 public native Method[] getMethods();
577 * Get the modifiers of this class. These can be decoded using Modifier,
578 * and is limited to one of public, protected, or private, and any of
579 * final, static, abstract, or interface. An array class has the same
580 * public, protected, or private modifier as its component type, and is
581 * marked final but not an interface. Primitive types and void are marked
582 * public and final, but not an interface.
584 * @return the modifiers of this class
585 * @see Modifer
586 * @since 1.1
588 public native int getModifiers ();
591 * Get the name of this class, separated by dots for package separators.
592 * If the class represents a primitive type, or void, then the
593 * name of the type as it appears in the Java programming language
594 * is returned. For instance, <code>Byte.TYPE.getName()</code>
595 * returns "byte".
597 * Arrays are specially encoded as shown on this table.
598 * <pre>
599 * array type [<em>element type</em>
600 * (note that the element type is encoded per
601 * this table)
602 * boolean Z
603 * byte B
604 * char C
605 * short S
606 * int I
607 * long J
608 * float F
609 * double D
610 * void V
611 * class or interface, alone: &lt;dotted name&gt;
612 * class or interface, as element type: L&lt;dotted name&gt;;
613 * </pre>
615 * @return the name of this class
617 public native String getName ();
620 * Get a resource URL using this class's package using the
621 * getClassLoader().getResource() method. If this class was loaded using
622 * the system classloader, ClassLoader.getSystemResource() is used instead.
624 * <p>If the name you supply is absolute (it starts with a <code>/</code>),
625 * then the leading <code>/</code> is removed and it is passed on to
626 * getResource(). If it is relative, the package name is prepended, and
627 * <code>.</code>'s are replaced with <code>/</code>.
629 * <p>The URL returned is system- and classloader-dependent, and could
630 * change across implementations.
632 * @param resourceName the name of the resource, generally a path
633 * @return the URL to the resource
634 * @throws NullPointerException if name is null
635 * @since 1.1
637 public URL getResource(String resourceName)
639 String name = resourcePath(resourceName);
640 ClassLoader loader = getClassLoaderInternal();
641 if (loader == null)
642 return ClassLoader.getSystemResource(name);
643 return loader.getResource(name);
647 * Get a resource using this class's package using the
648 * getClassLoader().getResourceAsStream() method. If this class was loaded
649 * using the system classloader, ClassLoader.getSystemResource() is used
650 * instead.
652 * <p>If the name you supply is absolute (it starts with a <code>/</code>),
653 * then the leading <code>/</code> is removed and it is passed on to
654 * getResource(). If it is relative, the package name is prepended, and
655 * <code>.</code>'s are replaced with <code>/</code>.
657 * <p>The URL returned is system- and classloader-dependent, and could
658 * change across implementations.
660 * @param resourceName the name of the resource, generally a path
661 * @return an InputStream with the contents of the resource in it, or null
662 * @throws NullPointerException if name is null
663 * @since 1.1
665 public InputStream getResourceAsStream(String resourceName)
667 String name = resourcePath(resourceName);
668 ClassLoader loader = getClassLoaderInternal();
669 if (loader == null)
670 return ClassLoader.getSystemResourceAsStream(name);
671 return loader.getResourceAsStream(name);
674 private String resourcePath(String resourceName)
676 if (resourceName.length() > 0)
678 if (resourceName.charAt(0) != '/')
680 String pkg = getPackagePortion(getName());
681 if (pkg.length() > 0)
682 resourceName = pkg.replace('.','/') + '/' + resourceName;
684 else
686 resourceName = resourceName.substring(1);
689 return resourceName;
693 * Get the signers of this class. This returns null if there are no signers,
694 * such as for primitive types or void.
696 * @return the signers of this class
697 * @since 1.1
699 public native Object[] getSigners ();
702 * Set the signers of this class.
704 * @param signers the signers of this class
706 native void setSigners(Object[] signers);
709 * Get the direct superclass of this class. If this is an interface,
710 * Object, a primitive type, or void, it will return null. If this is an
711 * array type, it will return Object.
713 * @return the direct superclass of this class
715 public native Class<? super T> getSuperclass ();
718 * Return whether this class is an array type.
720 * @return whether this class is an array type
721 * @since 1.1
723 public native boolean isArray ();
726 * Discover whether an instance of the Class parameter would be an
727 * instance of this Class as well. Think of doing
728 * <code>isInstance(c.newInstance())</code> or even
729 * <code>c.newInstance() instanceof (this class)</code>. While this
730 * checks widening conversions for objects, it must be exact for primitive
731 * types.
733 * @param c the class to check
734 * @return whether an instance of c would be an instance of this class
735 * as well
736 * @throws NullPointerException if c is null
737 * @since 1.1
739 public native boolean isAssignableFrom (Class<?> c);
742 * Discover whether an Object is an instance of this Class. Think of it
743 * as almost like <code>o instanceof (this class)</code>.
745 * @param o the Object to check
746 * @return whether o is an instance of this class
747 * @since 1.1
749 public native boolean isInstance (Object o);
752 * Check whether this class is an interface or not. Array types are not
753 * interfaces.
755 * @return whether this class is an interface or not
757 public native boolean isInterface ();
760 * Return whether this class is a primitive type. A primitive type class
761 * is a class representing a kind of "placeholder" for the various
762 * primitive types, or void. You can access the various primitive type
763 * classes through java.lang.Boolean.TYPE, java.lang.Integer.TYPE, etc.,
764 * or through boolean.class, int.class, etc.
766 * @return whether this class is a primitive type
767 * @see Boolean#TYPE
768 * @see Byte#TYPE
769 * @see Character#TYPE
770 * @see Short#TYPE
771 * @see Integer#TYPE
772 * @see Long#TYPE
773 * @see Float#TYPE
774 * @see Double#TYPE
775 * @see Void#TYPE
776 * @since 1.1
778 public native boolean isPrimitive ();
781 * Get a new instance of this class by calling the no-argument constructor.
782 * The class is initialized if it has not been already. A security check
783 * may be performed, with <code>checkMemberAccess(this, Member.PUBLIC)</code>
784 * as well as <code>checkPackageAccess</code> both having to succeed.
786 * @return a new instance of this class
787 * @throws InstantiationException if there is not a no-arg constructor
788 * for this class, including interfaces, abstract classes, arrays,
789 * primitive types, and void; or if an exception occurred during
790 * the constructor
791 * @throws IllegalAccessException if you are not allowed to access the
792 * no-arg constructor because of scoping reasons
793 * @throws SecurityException if the security check fails
794 * @throws ExceptionInInitializerError if class initialization caused by
795 * this call fails with an exception
797 public native T newInstance ()
798 throws InstantiationException, IllegalAccessException;
800 // We need a native method to retrieve the protection domain, because we
801 // can't add fields to java.lang.Class that are accessible from Java.
802 private native ProtectionDomain getProtectionDomain0();
805 * Returns the protection domain of this class. If the classloader did not
806 * record the protection domain when creating this class the unknown
807 * protection domain is returned which has a <code>null</code> code source
808 * and all permissions. A security check may be performed, with
809 * <code>RuntimePermission("getProtectionDomain")</code>.
811 * @return the protection domain
812 * @throws SecurityException if the security manager exists and the caller
813 * does not have <code>RuntimePermission("getProtectionDomain")</code>.
814 * @see RuntimePermission
815 * @since 1.2
817 public ProtectionDomain getProtectionDomain()
819 SecurityManager sm = System.getSecurityManager();
820 if (sm != null)
821 sm.checkPermission(VMClassLoader.protectionDomainPermission);
823 ProtectionDomain protectionDomain = getProtectionDomain0();
825 if (protectionDomain == null)
826 return VMClassLoader.unknownProtectionDomain;
827 else
828 return protectionDomain;
832 * Return the human-readable form of this Object. For an object, this
833 * is either "interface " or "class " followed by <code>getName()</code>,
834 * for primitive types and void it is just <code>getName()</code>.
836 * @return the human-readable form of this Object
838 public String toString()
840 if (isPrimitive())
841 return getName();
842 return (isInterface() ? "interface " : "class ") + getName();
846 * Returns the desired assertion status of this class, if it were to be
847 * initialized at this moment. The class assertion status, if set, is
848 * returned; the backup is the default package status; then if there is
849 * a class loader, that default is returned; and finally the system default
850 * is returned. This method seldom needs calling in user code, but exists
851 * for compilers to implement the assert statement. Note that there is no
852 * guarantee that the result of this method matches the class's actual
853 * assertion status.
855 * @return the desired assertion status
856 * @see ClassLoader#setClassAssertionStatus(String, boolean)
857 * @see ClassLoader#setPackageAssertionStatus(String, boolean)
858 * @see ClassLoader#setDefaultAssertionStatus(boolean)
859 * @since 1.4
861 public boolean desiredAssertionStatus()
863 ClassLoader c = getClassLoaderInternal();
864 Object status;
865 if (c == null)
866 return VMClassLoader.defaultAssertionStatus();
867 if (c.classAssertionStatus != null)
868 synchronized (c)
870 status = c.classAssertionStatus.get(getName());
871 if (status != null)
872 return status.equals(Boolean.TRUE);
874 else
876 status = ClassLoader.systemClassAssertionStatus.get(getName());
877 if (status != null)
878 return status.equals(Boolean.TRUE);
880 if (c.packageAssertionStatus != null)
881 synchronized (c)
883 String name = getPackagePortion(getName());
884 if ("".equals(name))
885 status = c.packageAssertionStatus.get(null);
886 else
889 status = c.packageAssertionStatus.get(name);
890 name = getPackagePortion(name);
892 while (! "".equals(name) && status == null);
893 if (status != null)
894 return status.equals(Boolean.TRUE);
896 else
898 String name = getPackagePortion(getName());
899 if ("".equals(name))
900 status = ClassLoader.systemPackageAssertionStatus.get(null);
901 else
904 status = ClassLoader.systemPackageAssertionStatus.get(name);
905 name = getPackagePortion(name);
907 while (! "".equals(name) && status == null);
908 if (status != null)
909 return status.equals(Boolean.TRUE);
911 return c.defaultAssertionStatus;
915 * Strip the last portion of the name (after the last dot).
917 * @param name the name to get package of
918 * @return the package name, or "" if no package
920 private static String getPackagePortion(String name)
922 int lastInd = name.lastIndexOf('.');
923 if (lastInd == -1)
924 return "";
925 return name.substring(0, lastInd);
929 * Perform security checks common to all of the methods that
930 * get members of this Class.
932 private void memberAccessCheck(int which)
934 SecurityManager sm = System.getSecurityManager();
935 if (sm != null)
937 sm.checkMemberAccess(this, which);
938 Package pkg = getPackage();
939 if (pkg != null)
940 sm.checkPackageAccess(pkg.getName());
946 * <p>
947 * Casts this class to represent a subclass of the specified class.
948 * This method is useful for `narrowing' the type of a class so that
949 * the class object, and instances of that class, can match the contract
950 * of a more restrictive method. For example, if this class has the
951 * static type of <code>Class&lt;Object&gt;</code>, and a dynamic type of
952 * <code>Class&lt;Rectangle&gt;</code>, then, assuming <code>Shape</code> is
953 * a superclass of <code>Rectangle</code>, this method can be used on
954 * this class with the parameter, <code>Class&lt;Shape&gt;</code>, to retain
955 * the same instance but with the type
956 * <code>Class&lt;? extends Shape&gt;</code>.
957 * </p>
958 * <p>
959 * If this class can be converted to an instance which is parameterised
960 * over a subtype of the supplied type, <code>U</code>, then this method
961 * returns an appropriately cast reference to this object. Otherwise,
962 * a <code>ClassCastException</code> is thrown.
963 * </p>
965 * @param klass the class object, the parameterized type (<code>U</code>) of
966 * which should be a superclass of the parameterized type of
967 * this instance.
968 * @return a reference to this object, appropriately cast.
969 * @throws ClassCastException if this class can not be converted to one
970 * which represents a subclass of the specified
971 * type, <code>U</code>.
972 * @since 1.5
974 public <U> Class<? extends U> asSubclass(Class<U> klass)
976 if (! klass.isAssignableFrom(this))
977 throw new ClassCastException();
978 return (Class<? extends U>) this;
982 * Returns the specified object, cast to this <code>Class</code>' type.
984 * @param obj the object to cast
985 * @throws ClassCastException if obj is not an instance of this class
986 * @since 1.5
988 public T cast(Object obj)
990 if (obj != null && ! isInstance(obj))
991 throw new ClassCastException();
992 return (T) obj;
996 * Returns the enumeration constants of this class, or
997 * null if this class is not an <code>Enum</code>.
999 * @return an array of <code>Enum</code> constants
1000 * associated with this class, or null if this
1001 * class is not an <code>enum</code>.
1002 * @since 1.5
1004 public T[] getEnumConstants()
1006 if (isEnum())
1010 Method m = getMethod("values");
1011 setAccessible(m);
1012 return (T[]) m.invoke(null);
1014 catch (NoSuchMethodException exception)
1016 throw new Error("Enum lacks values() method");
1018 catch (IllegalAccessException exception)
1020 throw new Error("Unable to access Enum class");
1022 catch (InvocationTargetException exception)
1024 throw new
1025 RuntimeException("The values method threw an exception",
1026 exception);
1029 else
1031 return null;
1036 * Returns true if this class is an <code>Enum</code>.
1038 * @return true if this is an enumeration class.
1039 * @since 1.5
1041 public native boolean isEnum();
1045 * Returns true if this class is a synthetic class, generated by
1046 * the compiler.
1048 * @return true if this is a synthetic class.
1049 * @since 1.5
1051 public native boolean isSynthetic();
1055 * Returns true if this class is an <code>Annotation</code>.
1057 * @return true if this is an annotation class.
1058 * @since 1.5
1060 public native boolean isAnnotation();
1064 * Returns the simple name for this class, as used in the source
1065 * code. For normal classes, this is the content returned by
1066 * <code>getName()</code> which follows the last ".". Anonymous
1067 * classes have no name, and so the result of calling this method is
1068 * "". The simple name of an array consists of the simple name of
1069 * its component type, followed by "[]". Thus, an array with the
1070 * component type of an anonymous class has a simple name of simply
1071 * "[]".
1073 * @return the simple name for this class.
1074 * @since 1.5
1076 public String getSimpleName()
1078 if (isAnonymousClass())
1079 return "";
1080 if (isArray())
1081 return getComponentType().getSimpleName() + "[]";
1083 String fullName = getName();
1084 Class enclosingClass = getEnclosingClass();
1085 if (enclosingClass == null)
1086 // It's a top level class.
1087 return fullName.substring(fullName.lastIndexOf(".") + 1);
1089 fullName = fullName.substring(enclosingClass.getName().length());
1091 // We've carved off the enclosing class name; now we must have '$'
1092 // followed optionally by digits, followed by the class name.
1093 int pos = 1;
1094 while (Character.isDigit(fullName.charAt(pos)))
1095 ++pos;
1096 fullName = fullName.substring(pos);
1098 return fullName;
1102 * Returns the class which immediately encloses this class. If this class
1103 * is a top-level class, this method returns <code>null</code>.
1105 * @return the immediate enclosing class, or <code>null</code> if this is
1106 * a top-level class.
1107 * @since 1.5
1109 public native Class<?> getEnclosingClass();
1112 * Returns the constructor which immediately encloses this class. If
1113 * this class is a top-level class, or a local or anonymous class
1114 * immediately enclosed by a type definition, instance initializer
1115 * or static initializer, then <code>null</code> is returned.
1117 * @return the immediate enclosing constructor if this class is
1118 * declared within a constructor. Otherwise, <code>null</code>
1119 * is returned.
1120 * @since 1.5
1122 public native Constructor<T> getEnclosingConstructor();
1125 * Returns the method which immediately encloses this class. If
1126 * this class is a top-level class, or a local or anonymous class
1127 * immediately enclosed by a type definition, instance initializer
1128 * or static initializer, then <code>null</code> is returned.
1130 * @return the immediate enclosing method if this class is
1131 * declared within a method. Otherwise, <code>null</code>
1132 * is returned.
1133 * @since 1.5
1135 public native Method getEnclosingMethod();
1137 private native String getClassSignature();
1140 * <p>
1141 * Returns an array of <code>Type</code> objects which represent the
1142 * interfaces directly implemented by this class or extended by this
1143 * interface.
1144 * </p>
1145 * <p>
1146 * If one of the superinterfaces is a parameterized type, then the
1147 * object returned for this interface reflects the actual type
1148 * parameters used in the source code. Type parameters are created
1149 * using the semantics specified by the <code>ParameterizedType</code>
1150 * interface, and only if an instance has not already been created.
1151 * </p>
1152 * <p>
1153 * The order of the interfaces in the array matches the order in which
1154 * the interfaces are declared. For classes which represent an array,
1155 * an array of two interfaces, <code>Cloneable</code> and
1156 * <code>Serializable</code>, is always returned, with the objects in
1157 * that order. A class representing a primitive type or void always
1158 * returns an array of zero size.
1159 * </p>
1161 * @return an array of interfaces implemented or extended by this class.
1162 * @throws GenericSignatureFormatError if the generic signature of one
1163 * of the interfaces does not comply with that specified by the Java
1164 * Virtual Machine specification, 3rd edition.
1165 * @throws TypeNotPresentException if any of the superinterfaces refers
1166 * to a non-existant type.
1167 * @throws MalformedParameterizedTypeException if any of the interfaces
1168 * refer to a parameterized type that can not be instantiated for
1169 * some reason.
1170 * @since 1.5
1171 * @see java.lang.reflect.ParameterizedType
1173 public Type[] getGenericInterfaces()
1175 if (isPrimitive())
1176 return new Type[0];
1178 String sig = getClassSignature();
1179 if (sig == null)
1180 return getInterfaces();
1182 ClassSignatureParser p = new ClassSignatureParser(this, sig);
1183 return p.getInterfaceTypes();
1187 * <p>
1188 * Returns a <code>Type</code> object representing the direct superclass,
1189 * whether class, interface, primitive type or void, of this class.
1190 * If this class is an array class, then a class instance representing
1191 * the <code>Object</code> class is returned. If this class is primitive,
1192 * an interface, or a representation of either the <code>Object</code>
1193 * class or void, then <code>null</code> is returned.
1194 * </p>
1195 * <p>
1196 * If the superclass is a parameterized type, then the
1197 * object returned for this interface reflects the actual type
1198 * parameters used in the source code. Type parameters are created
1199 * using the semantics specified by the <code>ParameterizedType</code>
1200 * interface, and only if an instance has not already been created.
1201 * </p>
1203 * @return the superclass of this class.
1204 * @throws GenericSignatureFormatError if the generic signature of the
1205 * class does not comply with that specified by the Java
1206 * Virtual Machine specification, 3rd edition.
1207 * @throws TypeNotPresentException if the superclass refers
1208 * to a non-existant type.
1209 * @throws MalformedParameterizedTypeException if the superclass
1210 * refers to a parameterized type that can not be instantiated for
1211 * some reason.
1212 * @since 1.5
1213 * @see java.lang.reflect.ParameterizedType
1215 public Type getGenericSuperclass()
1217 if (isArray())
1218 return Object.class;
1220 if (isPrimitive() || isInterface() || this == Object.class)
1221 return null;
1223 String sig = getClassSignature();
1224 if (sig == null)
1225 return getSuperclass();
1227 ClassSignatureParser p = new ClassSignatureParser(this, sig);
1228 return p.getSuperclassType();
1232 * Returns an array of <code>TypeVariable</code> objects that represents
1233 * the type variables declared by this class, in declaration order.
1234 * An array of size zero is returned if this class has no type
1235 * variables.
1237 * @return the type variables associated with this class.
1238 * @throws GenericSignatureFormatError if the generic signature does
1239 * not conform to the format specified in the Virtual Machine
1240 * specification, version 3.
1241 * @since 1.5
1243 public TypeVariable<Class<T>>[] getTypeParameters()
1245 String sig = getClassSignature();
1246 if (sig == null)
1247 return (TypeVariable<Class<T>>[])new TypeVariable[0];
1249 ClassSignatureParser p = new ClassSignatureParser(this, sig);
1250 return p.getTypeParameters();
1254 * Returns this class' annotation for the specified annotation type,
1255 * or <code>null</code> if no such annotation exists.
1257 * @param annotationClass the type of annotation to look for.
1258 * @return this class' annotation for the specified type, or
1259 * <code>null</code> if no such annotation exists.
1260 * @since 1.5
1262 public <A extends Annotation> A getAnnotation(Class<A> annotationClass)
1264 A foundAnnotation = null;
1265 Annotation[] annotations = getAnnotations();
1266 for (Annotation annotation : annotations)
1267 if (annotation.annotationType() == annotationClass)
1268 foundAnnotation = (A) annotation;
1269 return foundAnnotation;
1273 * Returns all annotations associated with this class. If there are
1274 * no annotations associated with this class, then a zero-length array
1275 * will be returned. The returned array may be modified by the client
1276 * code, but this will have no effect on the annotation content of this
1277 * class, and hence no effect on the return value of this method for
1278 * future callers.
1280 * @return this class' annotations.
1281 * @since 1.5
1283 public Annotation[] getAnnotations()
1285 HashMap<Class, Annotation> map = new HashMap<Class, Annotation>();
1286 for (Annotation a : getDeclaredAnnotations())
1287 map.put((Class) a.annotationType(), a);
1288 for (Class<? super T> s = getSuperclass();
1289 s != null;
1290 s = s.getSuperclass())
1292 for (Annotation a : s.getDeclaredAnnotations())
1294 Class k = (Class) a.annotationType();
1295 if (! map.containsKey(k) && k.isAnnotationPresent(Inherited.class))
1296 map.put(k, a);
1299 Collection<Annotation> v = map.values();
1300 return v.toArray(new Annotation[v.size()]);
1304 * <p>
1305 * Returns the canonical name of this class, as defined by section
1306 * 6.7 of the Java language specification. Each package, top-level class,
1307 * top-level interface and primitive type has a canonical name. A member
1308 * class has a canonical name, if its parent class has one. Likewise,
1309 * an array type has a canonical name, if its component type does.
1310 * Local or anonymous classes do not have canonical names.
1311 * </p>
1312 * <p>
1313 * The canonical name for top-level classes, top-level interfaces and
1314 * primitive types is always the same as the fully-qualified name.
1315 * For array types, the canonical name is the canonical name of its
1316 * component type with `[]' appended.
1317 * </p>
1318 * <p>
1319 * The canonical name of a member class always refers to the place where
1320 * the class was defined, and is composed of the canonical name of the
1321 * defining class and the simple name of the member class, joined by `.'.
1322 * For example, if a <code>Person</code> class has an inner class,
1323 * <code>M</code>, then both its fully-qualified name and canonical name
1324 * is <code>Person.M</code>. A subclass, <code>Staff</code>, of
1325 * <code>Person</code> refers to the same inner class by the fully-qualified
1326 * name of <code>Staff.M</code>, but its canonical name is still
1327 * <code>Person.M</code>.
1328 * </p>
1329 * <p>
1330 * Where no canonical name is present, <code>null</code> is returned.
1331 * </p>
1333 * @return the canonical name of the class, or <code>null</code> if the
1334 * class doesn't have a canonical name.
1335 * @since 1.5
1337 public String getCanonicalName()
1339 if (isArray())
1341 String componentName = getComponentType().getCanonicalName();
1342 if (componentName != null)
1343 return componentName + "[]";
1345 if (isMemberClass())
1347 String memberName = getDeclaringClass().getCanonicalName();
1348 if (memberName != null)
1349 return memberName + "." + getSimpleName();
1351 if (isLocalClass() || isAnonymousClass())
1352 return null;
1353 return getName();
1357 * Returns all annotations directly defined by this class. If there are
1358 * no annotations associated with this class, then a zero-length array
1359 * will be returned. The returned array may be modified by the client
1360 * code, but this will have no effect on the annotation content of this
1361 * class, and hence no effect on the return value of this method for
1362 * future callers.
1364 * @return the annotations directly defined by this class.
1365 * @since 1.5
1367 public Annotation[] getDeclaredAnnotations()
1369 Annotation[] result = getDeclaredAnnotationsInternal();
1370 if (result == null)
1371 result = new Annotation[0];
1372 return result;
1375 private native Annotation[] getDeclaredAnnotationsInternal();
1378 * Returns true if an annotation for the specified type is associated
1379 * with this class. This is primarily a short-hand for using marker
1380 * annotations.
1382 * @param annotationClass the type of annotation to look for.
1383 * @return true if an annotation exists for the specified type.
1384 * @since 1.5
1386 public boolean isAnnotationPresent(Class<? extends Annotation>
1387 annotationClass)
1389 return getAnnotation(annotationClass) != null;
1393 * Returns true if this object represents an anonymous class.
1395 * @return true if this object represents an anonymous class.
1396 * @since 1.5
1398 public native boolean isAnonymousClass();
1401 * Returns true if this object represents an local class.
1403 * @return true if this object represents an local class.
1404 * @since 1.5
1406 public native boolean isLocalClass();
1409 * Returns true if this object represents an member class.
1411 * @return true if this object represents an member class.
1412 * @since 1.5
1414 public native boolean isMemberClass();
1417 * Utility method for use by classes in this package.
1419 static void setAccessible(final AccessibleObject obj)
1421 AccessController.doPrivileged(new PrivilegedAction()
1423 public Object run()
1425 obj.setAccessible(true);
1426 return null;