1 /* Class.java -- Representation of a Java class.
2 Copyright (C) 1998, 1999, 2000, 2002, 2003, 2004, 2005, 2006
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)
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
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
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. */
41 import gnu.classpath.VMStackWalker;
42 import gnu.java.lang.reflect.ClassSignatureParser;
44 import java.io.InputStream;
45 import java.io.Serializable;
46 import java.lang.annotation.Annotation;
47 import java.lang.annotation.Inherited;
48 import java.lang.reflect.AnnotatedElement;
49 import java.lang.reflect.Constructor;
50 import java.lang.reflect.Field;
51 import java.lang.reflect.GenericDeclaration;
52 import java.lang.reflect.InvocationTargetException;
53 import java.lang.reflect.Member;
54 import java.lang.reflect.Method;
55 import java.lang.reflect.Modifier;
56 import java.lang.reflect.Type;
57 import java.lang.reflect.TypeVariable;
59 import java.security.AccessController;
60 import java.security.AllPermission;
61 import java.security.Permissions;
62 import java.security.PrivilegedAction;
63 import java.security.ProtectionDomain;
64 import java.util.ArrayList;
65 import java.util.Arrays;
66 import java.util.Collection;
67 import java.util.HashMap;
68 import java.util.HashSet;
72 * A Class represents a Java type. There will never be multiple Class
73 * objects with identical names and ClassLoaders. Primitive types, array
74 * types, and void also have a Class object.
76 * <p>Arrays with identical type and number of dimensions share the same class.
77 * The array class ClassLoader is the same as the ClassLoader of the element
78 * type of the array (which can be null to indicate the bootstrap classloader).
79 * The name of an array class is <code>[<signature format>;</code>.
81 * String[]'s class is <code>[Ljava.lang.String;</code>. boolean, byte,
82 * short, char, int, long, float and double have the "type name" of
83 * Z,B,S,C,I,J,F,D for the purposes of array classes. If it's a
84 * multidimensioned array, the same principle applies:
85 * <code>int[][][]</code> == <code>[[[I</code>.
87 * <p>There is no public constructor - Class objects are obtained only through
88 * the virtual machine, as defined in ClassLoaders.
90 * @serialData Class objects serialize specially:
91 * <code>TC_CLASS ClassDescriptor</code>. For more serialization information,
92 * see {@link ObjectStreamClass}.
95 * @author Eric Blake (ebb9@email.byu.edu)
96 * @author Tom Tromey (tromey@redhat.com)
97 * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
101 public final class Class<T>
102 implements Serializable, Type, AnnotatedElement, GenericDeclaration
105 * Compatible with JDK 1.0+.
107 private static final long serialVersionUID = 3206093459760846163L;
110 * Flag indicating a synthetic member.
111 * Note that this duplicates a constant in Modifier.
113 private static final int SYNTHETIC = 0x1000;
116 * Flag indiciating an annotation class.
118 private static final int ANNOTATION = 0x2000;
121 * Flag indicating an enum constant or an enum class.
122 * Note that this duplicates a constant in Modifier.
124 private static final int ENUM = 0x4000;
126 /** The class signers. */
127 private Object[] signers = null;
128 /** The class protection domain. */
129 private final transient ProtectionDomain pd;
131 /* We use an inner class, so that Class doesn't have a static initializer */
132 private static final class StaticData
134 static final ProtectionDomain unknownProtectionDomain;
138 Permissions permissions = new Permissions();
139 permissions.add(new AllPermission());
140 unknownProtectionDomain = new ProtectionDomain(null, permissions);
144 final transient Object vmdata;
146 /** newInstance() caches the default constructor */
147 private transient Constructor<T> constructor;
150 * Class is non-instantiable from Java code; only the VM can create
151 * instances of this class.
158 Class(Object vmdata, ProtectionDomain pd)
160 this.vmdata = vmdata;
161 // If the VM didn't supply a protection domain and the class is an array,
162 // we "inherit" the protection domain from the component type class. This
163 // saves the VM from having to worry about protection domains for array
165 if (pd == null && isArray())
166 this.pd = getComponentType().pd;
172 * Use the classloader of the current class to load, link, and initialize
173 * a class. This is equivalent to your code calling
174 * <code>Class.forName(name, true, getClass().getClassLoader())</code>.
176 * @param name the name of the class to find
177 * @return the Class object representing the class
178 * @throws ClassNotFoundException if the class was not found by the
180 * @throws LinkageError if linking the class fails
181 * @throws ExceptionInInitializerError if the class loads, but an exception
182 * occurs during initialization
184 public static Class<?> forName(String name) throws ClassNotFoundException
186 return VMClass.forName(name, true, VMStackWalker.getCallingClassLoader());
190 * Use the specified classloader to load and link a class. If the loader
191 * is null, this uses the bootstrap class loader (provide the security
192 * check succeeds). Unfortunately, this method cannot be used to obtain
193 * the Class objects for primitive types or for void, you have to use
194 * the fields in the appropriate java.lang wrapper classes.
196 * <p>Calls <code>classloader.loadclass(name, initialize)</code>.
198 * @param name the name of the class to find
199 * @param initialize whether or not to initialize the class at this time
200 * @param classloader the classloader to use to find the class; null means
201 * to use the bootstrap class loader
203 * @return the class object for the given class
205 * @throws ClassNotFoundException if the class was not found by the
207 * @throws LinkageError if linking the class fails
208 * @throws ExceptionInInitializerError if the class loads, but an exception
209 * occurs during initialization
210 * @throws SecurityException if the <code>classloader</code> argument
211 * is <code>null</code> and the caller does not have the
212 * <code>RuntimePermission("getClassLoader")</code> permission
216 public static Class<?> forName(String name, boolean initialize,
217 ClassLoader classloader)
218 throws ClassNotFoundException
220 if (classloader == null)
222 // Check if we may access the bootstrap classloader
223 SecurityManager sm = SecurityManager.current;
226 // Get the calling classloader
227 ClassLoader cl = VMStackWalker.getCallingClassLoader();
229 sm.checkPermission(new RuntimePermission("getClassLoader"));
232 return (Class<?>) VMClass.forName(name, initialize, classloader);
236 * Get all the public member classes and interfaces declared in this
237 * class or inherited from superclasses. This returns an array of length
238 * 0 if there are no member classes, including for primitive types. A
239 * security check may be performed, with
240 * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
241 * <code>checkPackageAccess</code> both having to succeed.
243 * @return all public member classes in this class
244 * @throws SecurityException if the security check fails
247 public Class<?>[] getClasses()
249 memberAccessCheck(Member.PUBLIC);
250 return internalGetClasses();
254 * Like <code>getClasses()</code> but without the security checks.
256 private Class<?>[] internalGetClasses()
258 ArrayList<Class> list = new ArrayList<Class>();
259 list.addAll(Arrays.asList(getDeclaredClasses(true)));
260 Class superClass = getSuperclass();
261 if (superClass != null)
262 list.addAll(Arrays.asList(superClass.internalGetClasses()));
263 return list.toArray(new Class<?>[list.size()]);
267 * Get the ClassLoader that loaded this class. If the class was loaded
268 * by the bootstrap classloader, this method will return null.
269 * If there is a security manager, and the caller's class loader is not
270 * an ancestor of the requested one, a security check of
271 * <code>RuntimePermission("getClassLoader")</code>
272 * must first succeed. Primitive types and void return null.
274 * @return the ClassLoader that loaded this class
275 * @throws SecurityException if the security check fails
277 * @see RuntimePermission
279 public ClassLoader getClassLoader()
284 ClassLoader loader = VMClass.getClassLoader(this);
285 // Check if we may get the classloader
286 SecurityManager sm = SecurityManager.current;
287 if (loader != null && sm != null)
289 // Get the calling classloader
290 ClassLoader cl = VMStackWalker.getCallingClassLoader();
291 if (cl != null && !cl.isAncestorOf(loader))
292 sm.checkPermission(new RuntimePermission("getClassLoader"));
298 * If this is an array, get the Class representing the type of array.
299 * Examples: "[[Ljava.lang.String;" would return "[Ljava.lang.String;", and
300 * calling getComponentType on that would give "java.lang.String". If
301 * this is not an array, returns null.
303 * @return the array type of this class, or null
307 public Class<?> getComponentType()
309 return VMClass.getComponentType (this);
313 * Get a public constructor declared in this class. If the constructor takes
314 * no argument, an array of zero elements and null are equivalent for the
315 * types argument. A security check may be performed, with
316 * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
317 * <code>checkPackageAccess</code> both having to succeed.
319 * @param types the type of each parameter
320 * @return the constructor
321 * @throws NoSuchMethodException if the constructor does not exist
322 * @throws SecurityException if the security check fails
323 * @see #getConstructors()
326 public Constructor<T> getConstructor(Class<?>... types)
327 throws NoSuchMethodException
329 memberAccessCheck(Member.PUBLIC);
330 Constructor[] constructors = getDeclaredConstructors(true);
331 for (int i = 0; i < constructors.length; i++)
333 Constructor constructor = constructors[i];
334 if (matchParameters(types, constructor.getParameterTypes()))
337 throw new NoSuchMethodException();
341 * Get all the public constructors of this class. This returns an array of
342 * length 0 if there are no constructors, including for primitive types,
343 * arrays, and interfaces. It does, however, include the default
344 * constructor if one was supplied by the compiler. A security check may
345 * be performed, with <code>checkMemberAccess(this, Member.PUBLIC)</code>
346 * as well as <code>checkPackageAccess</code> both having to succeed.
348 * @return all public constructors in this class
349 * @throws SecurityException if the security check fails
352 public Constructor<?>[] getConstructors()
354 memberAccessCheck(Member.PUBLIC);
355 return getDeclaredConstructors(true);
359 * Get a constructor declared in this class. If the constructor takes no
360 * argument, an array of zero elements and null are equivalent for the
361 * types argument. A security check may be performed, with
362 * <code>checkMemberAccess(this, Member.DECLARED)</code> as well as
363 * <code>checkPackageAccess</code> both having to succeed.
365 * @param types the type of each parameter
366 * @return the constructor
367 * @throws NoSuchMethodException if the constructor does not exist
368 * @throws SecurityException if the security check fails
369 * @see #getDeclaredConstructors()
372 public Constructor<T> getDeclaredConstructor(Class<?>... types)
373 throws NoSuchMethodException
375 memberAccessCheck(Member.DECLARED);
376 Constructor[] constructors = getDeclaredConstructors(false);
377 for (int i = 0; i < constructors.length; i++)
379 Constructor constructor = constructors[i];
380 if (matchParameters(types, constructor.getParameterTypes()))
383 throw new NoSuchMethodException();
387 * Get all the declared member classes and interfaces in this class, but
388 * not those inherited from superclasses. This returns an array of length
389 * 0 if there are no member classes, including for primitive types. A
390 * security check may be performed, with
391 * <code>checkMemberAccess(this, Member.DECLARED)</code> as well as
392 * <code>checkPackageAccess</code> both having to succeed.
394 * @return all declared member classes in this class
395 * @throws SecurityException if the security check fails
398 public Class<?>[] getDeclaredClasses()
400 memberAccessCheck(Member.DECLARED);
401 return getDeclaredClasses(false);
404 Class<?>[] getDeclaredClasses (boolean publicOnly)
406 return VMClass.getDeclaredClasses (this, publicOnly);
410 * Get all the declared constructors of this class. This returns an array of
411 * length 0 if there are no constructors, including for primitive types,
412 * arrays, and interfaces. It does, however, include the default
413 * constructor if one was supplied by the compiler. A security check may
414 * be performed, with <code>checkMemberAccess(this, Member.DECLARED)</code>
415 * as well as <code>checkPackageAccess</code> both having to succeed.
417 * @return all constructors in this class
418 * @throws SecurityException if the security check fails
421 public Constructor<?>[] getDeclaredConstructors()
423 memberAccessCheck(Member.DECLARED);
424 return getDeclaredConstructors(false);
427 Constructor<?>[] getDeclaredConstructors (boolean publicOnly)
429 return VMClass.getDeclaredConstructors (this, publicOnly);
433 * Get a field declared in this class, where name is its simple name. The
434 * implicit length field of arrays is not available. A security check may
435 * be performed, with <code>checkMemberAccess(this, Member.DECLARED)</code>
436 * as well as <code>checkPackageAccess</code> both having to succeed.
438 * @param name the name of the field
440 * @throws NoSuchFieldException if the field does not exist
441 * @throws SecurityException if the security check fails
442 * @see #getDeclaredFields()
445 public Field getDeclaredField(String name) throws NoSuchFieldException
447 memberAccessCheck(Member.DECLARED);
448 Field[] fields = getDeclaredFields(false);
449 for (int i = 0; i < fields.length; i++)
451 if (fields[i].getName().equals(name))
454 throw new NoSuchFieldException();
458 * Get all the declared fields in this class, but not those inherited from
459 * superclasses. This returns an array of length 0 if there are no fields,
460 * including for primitive types. This does not return the implicit length
461 * field of arrays. A security check may be performed, with
462 * <code>checkMemberAccess(this, Member.DECLARED)</code> as well as
463 * <code>checkPackageAccess</code> both having to succeed.
465 * @return all declared fields in this class
466 * @throws SecurityException if the security check fails
469 public Field[] getDeclaredFields()
471 memberAccessCheck(Member.DECLARED);
472 return getDeclaredFields(false);
475 Field[] getDeclaredFields (boolean publicOnly)
477 return VMClass.getDeclaredFields (this, publicOnly);
481 * Get a method declared in this class, where name is its simple name. The
482 * implicit methods of Object are not available from arrays or interfaces.
483 * Constructors (named "<init>" in the class file) and class initializers
484 * (name "<clinit>") are not available. The Virtual Machine allows
485 * multiple methods with the same signature but differing return types; in
486 * such a case the most specific return types are favored, then the final
487 * choice is arbitrary. If the method takes no argument, an array of zero
488 * elements and null are equivalent for the types argument. A security
489 * check may be performed, with
490 * <code>checkMemberAccess(this, Member.DECLARED)</code> as well as
491 * <code>checkPackageAccess</code> both having to succeed.
493 * @param methodName the name of the method
494 * @param types the type of each parameter
496 * @throws NoSuchMethodException if the method does not exist
497 * @throws SecurityException if the security check fails
498 * @see #getDeclaredMethods()
501 public Method getDeclaredMethod(String methodName, Class<?>... types)
502 throws NoSuchMethodException
504 memberAccessCheck(Member.DECLARED);
505 Method match = matchMethod(getDeclaredMethods(false), methodName, types);
507 throw new NoSuchMethodException(methodName);
512 * Get all the declared methods in this class, but not those inherited from
513 * superclasses. This returns an array of length 0 if there are no methods,
514 * including for primitive types. This does include the implicit methods of
515 * arrays and interfaces which mirror methods of Object, nor does it
516 * include constructors or the class initialization methods. The Virtual
517 * Machine allows multiple methods with the same signature but differing
518 * return types; all such methods are in the returned array. A security
519 * check may be performed, with
520 * <code>checkMemberAccess(this, Member.DECLARED)</code> as well as
521 * <code>checkPackageAccess</code> both having to succeed.
523 * @return all declared methods in this class
524 * @throws SecurityException if the security check fails
527 public Method[] getDeclaredMethods()
529 memberAccessCheck(Member.DECLARED);
530 return getDeclaredMethods(false);
533 Method[] getDeclaredMethods (boolean publicOnly)
535 return VMClass.getDeclaredMethods (this, publicOnly);
539 * If this is a nested or inner class, return the class that declared it.
540 * If not, return null.
542 * @return the declaring class of this class
545 public Class<?> getDeclaringClass()
547 return VMClass.getDeclaringClass (this);
551 * Get a public field declared or inherited in this class, where name is
552 * its simple name. If the class contains multiple accessible fields by
553 * that name, an arbitrary one is returned. The implicit length field of
554 * arrays is not available. A security check may be performed, with
555 * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
556 * <code>checkPackageAccess</code> both having to succeed.
558 * @param fieldName the name of the field
560 * @throws NoSuchFieldException if the field does not exist
561 * @throws SecurityException if the security check fails
565 public Field getField(String fieldName)
566 throws NoSuchFieldException
568 memberAccessCheck(Member.PUBLIC);
569 Field field = internalGetField(fieldName);
571 throw new NoSuchFieldException(fieldName);
576 * Get all the public fields declared in this class or inherited from
577 * superclasses. This returns an array of length 0 if there are no fields,
578 * including for primitive types. This does not return the implicit length
579 * field of arrays. A security check may be performed, with
580 * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
581 * <code>checkPackageAccess</code> both having to succeed.
583 * @return all public fields in this class
584 * @throws SecurityException if the security check fails
587 public Field[] getFields()
589 memberAccessCheck(Member.PUBLIC);
590 return internalGetFields();
594 * Like <code>getFields()</code> but without the security checks.
596 private Field[] internalGetFields()
598 HashSet<Field> set = new HashSet<Field>();
599 set.addAll(Arrays.asList(getDeclaredFields(true)));
600 Class[] interfaces = getInterfaces();
601 for (int i = 0; i < interfaces.length; i++)
602 set.addAll(Arrays.asList(interfaces[i].internalGetFields()));
603 Class superClass = getSuperclass();
604 if (superClass != null)
605 set.addAll(Arrays.asList(superClass.internalGetFields()));
606 return set.toArray(new Field[set.size()]);
610 * Returns the <code>Package</code> in which this class is defined
611 * Returns null when this information is not available from the
612 * classloader of this class.
614 * @return the package for this class, if it is available
617 public Package getPackage()
619 ClassLoader cl = getClassLoader();
621 return cl.getPackage(getPackagePortion(getName()));
623 return VMClassLoader.getPackage(getPackagePortion(getName()));
627 * Get the interfaces this class <em>directly</em> implements, in the
628 * order that they were declared. This returns an empty array, not null,
629 * for Object, primitives, void, and classes or interfaces with no direct
630 * superinterface. Array types return Cloneable and Serializable.
632 * @return the interfaces this class directly implements
634 public Class<?>[] getInterfaces()
636 return VMClass.getInterfaces (this);
639 private static final class MethodKey
642 private Class[] params;
643 private Class returnType;
649 params = m.getParameterTypes();
650 returnType = m.getReturnType();
651 hash = name.hashCode() ^ returnType.hashCode();
652 for(int i = 0; i < params.length; i++)
654 hash ^= params[i].hashCode();
658 public boolean equals(Object o)
660 if (o instanceof MethodKey)
662 MethodKey m = (MethodKey) o;
663 if (m.name.equals(name) && m.params.length == params.length
664 && m.returnType == returnType)
666 for (int i = 0; i < params.length; i++)
668 if (m.params[i] != params[i])
677 public int hashCode()
684 * Get a public method declared or inherited in this class, where name is
685 * its simple name. The implicit methods of Object are not available from
686 * interfaces. Constructors (named "<init>" in the class file) and class
687 * initializers (name "<clinit>") are not available. The Virtual
688 * Machine allows multiple methods with the same signature but differing
689 * return types, and the class can inherit multiple methods of the same
690 * return type; in such a case the most specific return types are favored,
691 * then the final choice is arbitrary. If the method takes no argument, an
692 * array of zero elements and null are equivalent for the types argument.
693 * A security check may be performed, with
694 * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
695 * <code>checkPackageAccess</code> both having to succeed.
697 * @param methodName the name of the method
698 * @param types the type of each parameter
700 * @throws NoSuchMethodException if the method does not exist
701 * @throws SecurityException if the security check fails
705 public Method getMethod(String methodName, Class<?>... types)
706 throws NoSuchMethodException
708 memberAccessCheck(Member.PUBLIC);
709 Method method = internalGetMethod(methodName, types);
711 throw new NoSuchMethodException(methodName);
716 * Like <code>getMethod(String,Class[])</code> but without the security
717 * checks and returns null instead of throwing NoSuchMethodException.
719 private Method internalGetMethod(String methodName, Class[] args)
721 Method match = matchMethod(getDeclaredMethods(true), methodName, args);
724 Class superClass = getSuperclass();
725 if (superClass != null)
727 match = superClass.internalGetMethod(methodName, args);
731 Class[] interfaces = getInterfaces();
732 for (int i = 0; i < interfaces.length; i++)
734 match = interfaces[i].internalGetMethod(methodName, args);
742 * Find the best matching method in <code>list</code> according to
743 * the definition of ``best matching'' used by <code>getMethod()</code>
746 * Returns the method if any, otherwise <code>null</code>.
748 * @param list List of methods to search
749 * @param name Name of method
750 * @param args Method parameter types
751 * @see #getMethod(String, Class[])
753 private static Method matchMethod(Method[] list, String name, Class[] args)
756 for (int i = 0; i < list.length; i++)
758 Method method = list[i];
759 if (!method.getName().equals(name))
761 if (!matchParameters(args, method.getParameterTypes()))
764 || match.getReturnType().isAssignableFrom(method.getReturnType()))
771 * Check for an exact match between parameter type lists.
772 * Either list may be <code>null</code> to mean a list of
775 private static boolean matchParameters(Class[] types1, Class[] types2)
778 return types2 == null || types2.length == 0;
780 return types1 == null || types1.length == 0;
781 if (types1.length != types2.length)
783 for (int i = 0; i < types1.length; i++)
785 if (types1[i] != types2[i])
792 * Get all the public methods declared in this class or inherited from
793 * superclasses. This returns an array of length 0 if there are no methods,
794 * including for primitive types. This does not include the implicit
795 * methods of interfaces which mirror methods of Object, nor does it
796 * include constructors or the class initialization methods. The Virtual
797 * Machine allows multiple methods with the same signature but differing
798 * return types; all such methods are in the returned array. A security
799 * check may be performed, with
800 * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
801 * <code>checkPackageAccess</code> both having to succeed.
803 * @return all public methods in this class
804 * @throws SecurityException if the security check fails
807 public Method[] getMethods()
809 memberAccessCheck(Member.PUBLIC);
810 // NOTE the API docs claim that no methods are returned for arrays,
811 // but Sun's implementation *does* return the public methods of Object
812 // (as would be expected), so we follow their implementation instead
813 // of their documentation.
814 return internalGetMethods();
818 * Like <code>getMethods()</code> but without the security checks.
820 private Method[] internalGetMethods()
822 HashMap<MethodKey,Method> map = new HashMap<MethodKey,Method>();
824 Class[] interfaces = getInterfaces();
825 for(int i = 0; i < interfaces.length; i++)
827 methods = interfaces[i].internalGetMethods();
828 for(int j = 0; j < methods.length; j++)
830 map.put(new MethodKey(methods[j]), methods[j]);
833 Class superClass = getSuperclass();
834 if(superClass != null)
836 methods = superClass.internalGetMethods();
837 for(int i = 0; i < methods.length; i++)
839 map.put(new MethodKey(methods[i]), methods[i]);
842 methods = getDeclaredMethods(true);
843 for(int i = 0; i < methods.length; i++)
845 map.put(new MethodKey(methods[i]), methods[i]);
847 return map.values().toArray(new Method[map.size()]);
851 * Get the modifiers of this class. These can be decoded using Modifier,
852 * and is limited to one of public, protected, or private, and any of
853 * final, static, abstract, or interface. An array class has the same
854 * public, protected, or private modifier as its component type, and is
855 * marked final but not an interface. Primitive types and void are marked
856 * public and final, but not an interface.
858 * @return the modifiers of this class
862 public int getModifiers()
864 int mod = VMClass.getModifiers (this, false);
865 return (mod & (Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE |
866 Modifier.FINAL | Modifier.STATIC | Modifier.ABSTRACT |
867 Modifier.INTERFACE));
871 * Get the name of this class, separated by dots for package separators.
872 * If the class represents a primitive type, or void, then the
873 * name of the type as it appears in the Java programming language
874 * is returned. For instance, <code>Byte.TYPE.getName()</code>
877 * Arrays are specially encoded as shown on this table.
879 * array type [<em>element type</em>
880 * (note that the element type is encoded per
891 * class or interface, alone: <dotted name>
892 * class or interface, as element type: L<dotted name>;
895 * @return the name of this class
897 public String getName()
899 return VMClass.getName (this);
903 * Get a resource URL using this class's package using the
904 * getClassLoader().getResource() method. If this class was loaded using
905 * the system classloader, ClassLoader.getSystemResource() is used instead.
907 * <p>If the name you supply is absolute (it starts with a <code>/</code>),
908 * then the leading <code>/</code> is removed and it is passed on to
909 * getResource(). If it is relative, the package name is prepended, and
910 * <code>.</code>'s are replaced with <code>/</code>.
912 * <p>The URL returned is system- and classloader-dependent, and could
913 * change across implementations.
915 * @param resourceName the name of the resource, generally a path
916 * @return the URL to the resource
917 * @throws NullPointerException if name is null
920 public URL getResource(String resourceName)
922 String name = resourcePath(resourceName);
923 ClassLoader loader = getClassLoader();
925 return ClassLoader.getSystemResource(name);
926 return loader.getResource(name);
930 * Get a resource using this class's package using the
931 * getClassLoader().getResourceAsStream() method. If this class was loaded
932 * using the system classloader, ClassLoader.getSystemResource() is used
935 * <p>If the name you supply is absolute (it starts with a <code>/</code>),
936 * then the leading <code>/</code> is removed and it is passed on to
937 * getResource(). If it is relative, the package name is prepended, and
938 * <code>.</code>'s are replaced with <code>/</code>.
940 * <p>The URL returned is system- and classloader-dependent, and could
941 * change across implementations.
943 * @param resourceName the name of the resource, generally a path
944 * @return an InputStream with the contents of the resource in it, or null
945 * @throws NullPointerException if name is null
948 public InputStream getResourceAsStream(String resourceName)
950 String name = resourcePath(resourceName);
951 ClassLoader loader = getClassLoader();
953 return ClassLoader.getSystemResourceAsStream(name);
954 return loader.getResourceAsStream(name);
957 private String resourcePath(String resourceName)
959 if (resourceName.length() > 0)
961 if (resourceName.charAt(0) != '/')
963 String pkg = getPackagePortion(getName());
964 if (pkg.length() > 0)
965 resourceName = pkg.replace('.','/') + '/' + resourceName;
969 resourceName = resourceName.substring(1);
976 * Get the signers of this class. This returns null if there are no signers,
977 * such as for primitive types or void.
979 * @return the signers of this class
982 public Object[] getSigners()
984 return signers == null ? null : (Object[]) signers.clone ();
988 * Set the signers of this class.
990 * @param signers the signers of this class
992 void setSigners(Object[] signers)
994 this.signers = signers;
998 * Get the direct superclass of this class. If this is an interface,
999 * Object, a primitive type, or void, it will return null. If this is an
1000 * array type, it will return Object.
1002 * @return the direct superclass of this class
1004 public Class<? super T> getSuperclass()
1006 return VMClass.getSuperclass (this);
1010 * Return whether this class is an array type.
1012 * @return whether this class is an array type
1015 public boolean isArray()
1017 return VMClass.isArray (this);
1021 * Discover whether an instance of the Class parameter would be an
1022 * instance of this Class as well. Think of doing
1023 * <code>isInstance(c.newInstance())</code> or even
1024 * <code>c.newInstance() instanceof (this class)</code>. While this
1025 * checks widening conversions for objects, it must be exact for primitive
1028 * @param c the class to check
1029 * @return whether an instance of c would be an instance of this class
1031 * @throws NullPointerException if c is null
1034 public boolean isAssignableFrom(Class<?> c)
1036 return VMClass.isAssignableFrom (this, c);
1040 * Discover whether an Object is an instance of this Class. Think of it
1041 * as almost like <code>o instanceof (this class)</code>.
1043 * @param o the Object to check
1044 * @return whether o is an instance of this class
1047 public boolean isInstance(Object o)
1049 return VMClass.isInstance (this, o);
1053 * Check whether this class is an interface or not. Array types are not
1056 * @return whether this class is an interface or not
1058 public boolean isInterface()
1060 return VMClass.isInterface (this);
1064 * Return whether this class is a primitive type. A primitive type class
1065 * is a class representing a kind of "placeholder" for the various
1066 * primitive types, or void. You can access the various primitive type
1067 * classes through java.lang.Boolean.TYPE, java.lang.Integer.TYPE, etc.,
1068 * or through boolean.class, int.class, etc.
1070 * @return whether this class is a primitive type
1073 * @see Character#TYPE
1082 public boolean isPrimitive()
1084 return VMClass.isPrimitive (this);
1088 * Get a new instance of this class by calling the no-argument constructor.
1089 * The class is initialized if it has not been already. A security check
1090 * may be performed, with <code>checkMemberAccess(this, Member.PUBLIC)</code>
1091 * as well as <code>checkPackageAccess</code> both having to succeed.
1093 * @return a new instance of this class
1094 * @throws InstantiationException if there is not a no-arg constructor
1095 * for this class, including interfaces, abstract classes, arrays,
1096 * primitive types, and void; or if an exception occurred during
1098 * @throws IllegalAccessException if you are not allowed to access the
1099 * no-arg constructor because of scoping reasons
1100 * @throws SecurityException if the security check fails
1101 * @throws ExceptionInInitializerError if class initialization caused by
1102 * this call fails with an exception
1104 public T newInstance()
1105 throws InstantiationException, IllegalAccessException
1107 memberAccessCheck(Member.PUBLIC);
1108 Constructor<T> constructor;
1111 constructor = this.constructor;
1113 if (constructor == null)
1115 Constructor[] constructors = getDeclaredConstructors(false);
1116 for (int i = 0; i < constructors.length; i++)
1118 if (constructors[i].getParameterTypes().length == 0)
1120 constructor = constructors[i];
1124 if (constructor == null)
1125 throw new InstantiationException(getName());
1126 if (!Modifier.isPublic(constructor.getModifiers())
1127 || !Modifier.isPublic(VMClass.getModifiers(this, true)))
1129 final Constructor finalConstructor = constructor;
1130 AccessController.doPrivileged(new PrivilegedAction()
1134 finalConstructor.setAccessible(true);
1141 if (this.constructor == null)
1142 this.constructor = constructor;
1145 int modifiers = constructor.getModifiers();
1146 if (!Modifier.isPublic(modifiers)
1147 || !Modifier.isPublic(VMClass.getModifiers(this, true)))
1149 Class caller = VMStackWalker.getCallingClass();
1150 if (caller != null &&
1152 (Modifier.isPrivate(modifiers)
1153 || getClassLoader() != caller.getClassLoader()
1154 || !getPackagePortion(getName())
1155 .equals(getPackagePortion(caller.getName()))))
1156 throw new IllegalAccessException(getName()
1157 + " has an inaccessible constructor");
1161 return constructor.newInstance(null);
1163 catch (InvocationTargetException e)
1165 VMClass.throwException(e.getTargetException());
1166 throw (InternalError) new InternalError
1167 ("VMClass.throwException returned").initCause(e);
1172 * Returns the protection domain of this class. If the classloader did not
1173 * record the protection domain when creating this class the unknown
1174 * protection domain is returned which has a <code>null</code> code source
1175 * and all permissions. A security check may be performed, with
1176 * <code>RuntimePermission("getProtectionDomain")</code>.
1178 * @return the protection domain
1179 * @throws SecurityException if the security manager exists and the caller
1180 * does not have <code>RuntimePermission("getProtectionDomain")</code>.
1181 * @see RuntimePermission
1184 public ProtectionDomain getProtectionDomain()
1186 SecurityManager sm = SecurityManager.current;
1188 sm.checkPermission(new RuntimePermission("getProtectionDomain"));
1190 return pd == null ? StaticData.unknownProtectionDomain : pd;
1194 * Return the human-readable form of this Object. For an object, this
1195 * is either "interface " or "class " followed by <code>getName()</code>,
1196 * for primitive types and void it is just <code>getName()</code>.
1198 * @return the human-readable form of this Object
1200 public String toString()
1204 return (isInterface() ? "interface " : "class ") + getName();
1208 * Returns the desired assertion status of this class, if it were to be
1209 * initialized at this moment. The class assertion status, if set, is
1210 * returned; the backup is the default package status; then if there is
1211 * a class loader, that default is returned; and finally the system default
1212 * is returned. This method seldom needs calling in user code, but exists
1213 * for compilers to implement the assert statement. Note that there is no
1214 * guarantee that the result of this method matches the class's actual
1217 * @return the desired assertion status
1218 * @see ClassLoader#setClassAssertionStatus(String, boolean)
1219 * @see ClassLoader#setPackageAssertionStatus(String, boolean)
1220 * @see ClassLoader#setDefaultAssertionStatus(boolean)
1223 public boolean desiredAssertionStatus()
1225 ClassLoader c = getClassLoader();
1228 return VMClassLoader.defaultAssertionStatus();
1229 if (c.classAssertionStatus != null)
1232 status = c.classAssertionStatus.get(getName());
1234 return status.equals(Boolean.TRUE);
1238 status = ClassLoader.StaticData.
1239 systemClassAssertionStatus.get(getName());
1241 return status.equals(Boolean.TRUE);
1243 if (c.packageAssertionStatus != null)
1246 String name = getPackagePortion(getName());
1247 if ("".equals(name))
1248 status = c.packageAssertionStatus.get(null);
1252 status = c.packageAssertionStatus.get(name);
1253 name = getPackagePortion(name);
1255 while (! "".equals(name) && status == null);
1257 return status.equals(Boolean.TRUE);
1261 String name = getPackagePortion(getName());
1262 if ("".equals(name))
1263 status = ClassLoader.StaticData.
1264 systemPackageAssertionStatus.get(null);
1268 status = ClassLoader.StaticData.
1269 systemPackageAssertionStatus.get(name);
1270 name = getPackagePortion(name);
1272 while (! "".equals(name) && status == null);
1274 return status.equals(Boolean.TRUE);
1276 return c.defaultAssertionStatus;
1281 * Casts this class to represent a subclass of the specified class.
1282 * This method is useful for `narrowing' the type of a class so that
1283 * the class object, and instances of that class, can match the contract
1284 * of a more restrictive method. For example, if this class has the
1285 * static type of <code>Class<Object></code>, and a dynamic type of
1286 * <code>Class<Rectangle></code>, then, assuming <code>Shape</code> is
1287 * a superclass of <code>Rectangle</code>, this method can be used on
1288 * this class with the parameter, <code>Class<Shape></code>, to retain
1289 * the same instance but with the type
1290 * <code>Class<? extends Shape></code>.
1293 * If this class can be converted to an instance which is parameterised
1294 * over a subtype of the supplied type, <code>U</code>, then this method
1295 * returns an appropriately cast reference to this object. Otherwise,
1296 * a <code>ClassCastException</code> is thrown.
1299 * @param klass the class object, the parameterized type (<code>U</code>) of
1300 * which should be a superclass of the parameterized type of
1302 * @return a reference to this object, appropriately cast.
1303 * @throws ClassCastException if this class can not be converted to one
1304 * which represents a subclass of the specified
1305 * type, <code>U</code>.
1308 public <U> Class<? extends U> asSubclass(Class<U> klass)
1310 if (! klass.isAssignableFrom(this))
1311 throw new ClassCastException();
1312 return (Class<? extends U>) this;
1316 * Returns the specified object, cast to this <code>Class</code>' type.
1318 * @param obj the object to cast
1319 * @throws ClassCastException if obj is not an instance of this class
1322 public T cast(Object obj)
1324 if (obj != null && ! isInstance(obj))
1325 throw new ClassCastException();
1330 * Like <code>getField(String)</code> but without the security checks and
1331 * returns null instead of throwing NoSuchFieldException.
1333 private Field internalGetField(String name)
1335 Field[] fields = getDeclaredFields(true);
1336 for (int i = 0; i < fields.length; i++)
1338 Field field = fields[i];
1339 if (field.getName().equals(name))
1342 Class[] interfaces = getInterfaces();
1343 for (int i = 0; i < interfaces.length; i++)
1345 Field field = interfaces[i].internalGetField(name);
1349 Class superClass = getSuperclass();
1350 if (superClass != null)
1351 return superClass.internalGetField(name);
1356 * Strip the last portion of the name (after the last dot).
1358 * @param name the name to get package of
1359 * @return the package name, or "" if no package
1361 private static String getPackagePortion(String name)
1363 int lastInd = name.lastIndexOf('.');
1366 return name.substring(0, lastInd);
1370 * Perform security checks common to all of the methods that
1371 * get members of this Class.
1373 private void memberAccessCheck(int which)
1375 SecurityManager sm = SecurityManager.current;
1378 sm.checkMemberAccess(this, which);
1379 Package pkg = getPackage();
1381 sm.checkPackageAccess(pkg.getName());
1386 * Returns the enumeration constants of this class, or
1387 * null if this class is not an <code>Enum</code>.
1389 * @return an array of <code>Enum</code> constants
1390 * associated with this class, or null if this
1391 * class is not an <code>enum</code>.
1394 public T[] getEnumConstants()
1400 return (T[]) getMethod("values").invoke(null);
1402 catch (NoSuchMethodException exception)
1404 throw new Error("Enum lacks values() method");
1406 catch (IllegalAccessException exception)
1408 throw new Error("Unable to access Enum class");
1410 catch (InvocationTargetException exception)
1413 RuntimeException("The values method threw an exception",
1424 * Returns true if this class is an <code>Enum</code>.
1426 * @return true if this is an enumeration class.
1429 public boolean isEnum()
1431 int mod = VMClass.getModifiers (this, true);
1432 return (mod & ENUM) != 0;
1436 * Returns true if this class is a synthetic class, generated by
1439 * @return true if this is a synthetic class.
1442 public boolean isSynthetic()
1444 int mod = VMClass.getModifiers (this, true);
1445 return (mod & SYNTHETIC) != 0;
1449 * Returns true if this class is an <code>Annotation</code>.
1451 * @return true if this is an annotation class.
1454 public boolean isAnnotation()
1456 int mod = VMClass.getModifiers (this, true);
1457 return (mod & ANNOTATION) != 0;
1461 * Returns the simple name for this class, as used in the source
1462 * code. For normal classes, this is the content returned by
1463 * <code>getName()</code> which follows the last ".". Anonymous
1464 * classes have no name, and so the result of calling this method is
1465 * "". The simple name of an array consists of the simple name of
1466 * its component type, followed by "[]". Thus, an array with the
1467 * component type of an anonymous class has a simple name of simply
1470 * @return the simple name for this class.
1473 public String getSimpleName()
1475 return VMClass.getSimpleName(this);
1479 * Returns this class' annotation for the specified annotation type,
1480 * or <code>null</code> if no such annotation exists.
1482 * @param annotationClass the type of annotation to look for.
1483 * @return this class' annotation for the specified type, or
1484 * <code>null</code> if no such annotation exists.
1487 public <A extends Annotation> A getAnnotation(Class<A> annotationClass)
1489 A foundAnnotation = null;
1490 Annotation[] annotations = getAnnotations();
1491 for (Annotation annotation : annotations)
1492 if (annotation.annotationType() == annotationClass)
1493 foundAnnotation = (A) annotation;
1494 return foundAnnotation;
1498 * Returns all annotations associated with this class. If there are
1499 * no annotations associated with this class, then a zero-length array
1500 * will be returned. The returned array may be modified by the client
1501 * code, but this will have no effect on the annotation content of this
1502 * class, and hence no effect on the return value of this method for
1505 * @return this class' annotations.
1508 public Annotation[] getAnnotations()
1510 HashMap<Class, Annotation> map = new HashMap<Class, Annotation>();
1511 for (Annotation a : getDeclaredAnnotations())
1512 map.put((Class) a.annotationType(), a);
1513 for (Class<? super T> s = getSuperclass();
1515 s = s.getSuperclass())
1517 for (Annotation a : s.getDeclaredAnnotations())
1519 Class k = (Class) a.annotationType();
1520 if (! map.containsKey(k) && k.isAnnotationPresent(Inherited.class))
1524 Collection<Annotation> v = map.values();
1525 return v.toArray(new Annotation[v.size()]);
1530 * Returns the canonical name of this class, as defined by section
1531 * 6.7 of the Java language specification. Each package, top-level class,
1532 * top-level interface and primitive type has a canonical name. A member
1533 * class has a canonical name, if its parent class has one. Likewise,
1534 * an array type has a canonical name, if its component type does.
1535 * Local or anonymous classes do not have canonical names.
1538 * The canonical name for top-level classes, top-level interfaces and
1539 * primitive types is always the same as the fully-qualified name.
1540 * For array types, the canonical name is the canonical name of its
1541 * component type with `[]' appended.
1544 * The canonical name of a member class always refers to the place where
1545 * the class was defined, and is composed of the canonical name of the
1546 * defining class and the simple name of the member class, joined by `.'.
1547 * For example, if a <code>Person</code> class has an inner class,
1548 * <code>M</code>, then both its fully-qualified name and canonical name
1549 * is <code>Person.M</code>. A subclass, <code>Staff</code>, of
1550 * <code>Person</code> refers to the same inner class by the fully-qualified
1551 * name of <code>Staff.M</code>, but its canonical name is still
1552 * <code>Person.M</code>.
1555 * Where no canonical name is present, <code>null</code> is returned.
1558 * @return the canonical name of the class, or <code>null</code> if the
1559 * class doesn't have a canonical name.
1562 public String getCanonicalName()
1564 return VMClass.getCanonicalName(this);
1568 * Returns all annotations directly defined by this class. If there are
1569 * no annotations associated with this class, then a zero-length array
1570 * will be returned. The returned array may be modified by the client
1571 * code, but this will have no effect on the annotation content of this
1572 * class, and hence no effect on the return value of this method for
1575 * @return the annotations directly defined by this class.
1578 public Annotation[] getDeclaredAnnotations()
1580 return VMClass.getDeclaredAnnotations(this);
1584 * Returns the class which immediately encloses this class. If this class
1585 * is a top-level class, this method returns <code>null</code>.
1587 * @return the immediate enclosing class, or <code>null</code> if this is
1588 * a top-level class.
1591 public Class<?> getEnclosingClass()
1593 return VMClass.getEnclosingClass(this);
1597 * Returns the constructor which immediately encloses this class. If
1598 * this class is a top-level class, or a local or anonymous class
1599 * immediately enclosed by a type definition, instance initializer
1600 * or static initializer, then <code>null</code> is returned.
1602 * @return the immediate enclosing constructor if this class is
1603 * declared within a constructor. Otherwise, <code>null</code>
1607 public Constructor<?> getEnclosingConstructor()
1609 return VMClass.getEnclosingConstructor(this);
1613 * Returns the method which immediately encloses this class. If
1614 * this class is a top-level class, or a local or anonymous class
1615 * immediately enclosed by a type definition, instance initializer
1616 * or static initializer, then <code>null</code> is returned.
1618 * @return the immediate enclosing method if this class is
1619 * declared within a method. Otherwise, <code>null</code>
1623 public Method getEnclosingMethod()
1625 return VMClass.getEnclosingMethod(this);
1630 * Returns an array of <code>Type</code> objects which represent the
1631 * interfaces directly implemented by this class or extended by this
1635 * If one of the superinterfaces is a parameterized type, then the
1636 * object returned for this interface reflects the actual type
1637 * parameters used in the source code. Type parameters are created
1638 * using the semantics specified by the <code>ParameterizedType</code>
1639 * interface, and only if an instance has not already been created.
1642 * The order of the interfaces in the array matches the order in which
1643 * the interfaces are declared. For classes which represent an array,
1644 * an array of two interfaces, <code>Cloneable</code> and
1645 * <code>Serializable</code>, is always returned, with the objects in
1646 * that order. A class representing a primitive type or void always
1647 * returns an array of zero size.
1650 * @return an array of interfaces implemented or extended by this class.
1651 * @throws GenericSignatureFormatError if the generic signature of one
1652 * of the interfaces does not comply with that specified by the Java
1653 * Virtual Machine specification, 3rd edition.
1654 * @throws TypeNotPresentException if any of the superinterfaces refers
1655 * to a non-existant type.
1656 * @throws MalformedParameterizedTypeException if any of the interfaces
1657 * refer to a parameterized type that can not be instantiated for
1660 * @see java.lang.reflect.ParameterizedType
1662 public Type[] getGenericInterfaces()
1667 String sig = VMClass.getClassSignature(this);
1669 return getInterfaces();
1671 ClassSignatureParser p = new ClassSignatureParser(this, sig);
1672 return p.getInterfaceTypes();
1677 * Returns a <code>Type</code> object representing the direct superclass,
1678 * whether class, interface, primitive type or void, of this class.
1679 * If this class is an array class, then a class instance representing
1680 * the <code>Object</code> class is returned. If this class is primitive,
1681 * an interface, or a representation of either the <code>Object</code>
1682 * class or void, then <code>null</code> is returned.
1685 * If the superclass is a parameterized type, then the
1686 * object returned for this interface reflects the actual type
1687 * parameters used in the source code. Type parameters are created
1688 * using the semantics specified by the <code>ParameterizedType</code>
1689 * interface, and only if an instance has not already been created.
1692 * @return the superclass of this class.
1693 * @throws GenericSignatureFormatError if the generic signature of the
1694 * class does not comply with that specified by the Java
1695 * Virtual Machine specification, 3rd edition.
1696 * @throws TypeNotPresentException if the superclass refers
1697 * to a non-existant type.
1698 * @throws MalformedParameterizedTypeException if the superclass
1699 * refers to a parameterized type that can not be instantiated for
1702 * @see java.lang.reflect.ParameterizedType
1704 public Type getGenericSuperclass()
1707 return Object.class;
1709 if (isPrimitive() || isInterface() || this == Object.class)
1712 String sig = VMClass.getClassSignature(this);
1714 return getSuperclass();
1716 ClassSignatureParser p = new ClassSignatureParser(this, sig);
1717 return p.getSuperclassType();
1721 * Returns an array of <code>TypeVariable</code> objects that represents
1722 * the type variables declared by this class, in declaration order.
1723 * An array of size zero is returned if this class has no type
1726 * @return the type variables associated with this class.
1727 * @throws GenericSignatureFormatError if the generic signature does
1728 * not conform to the format specified in the Virtual Machine
1729 * specification, version 3.
1732 public TypeVariable<Class<T>>[] getTypeParameters()
1734 String sig = VMClass.getClassSignature(this);
1736 return (TypeVariable<Class<T>>[])new TypeVariable[0];
1738 ClassSignatureParser p = new ClassSignatureParser(this, sig);
1739 return p.getTypeParameters();
1743 * Returns true if an annotation for the specified type is associated
1744 * with this class. This is primarily a short-hand for using marker
1747 * @param annotationClass the type of annotation to look for.
1748 * @return true if an annotation exists for the specified type.
1751 public boolean isAnnotationPresent(Class<? extends Annotation>
1754 return getAnnotation(annotationClass) != null;
1758 * Returns true if this object represents an anonymous class.
1760 * @return true if this object represents an anonymous class.
1763 public boolean isAnonymousClass()
1765 return VMClass.isAnonymousClass(this);
1769 * Returns true if this object represents an local class.
1771 * @return true if this object represents an local class.
1774 public boolean isLocalClass()
1776 return VMClass.isLocalClass(this);
1780 * Returns true if this object represents an member class.
1782 * @return true if this object represents an member class.
1785 public boolean isMemberClass()
1787 return VMClass.isMemberClass(this);