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.AccessibleObject;
49 import java.lang.reflect.AnnotatedElement;
50 import java.lang.reflect.Constructor;
51 import java.lang.reflect.Field;
52 import java.lang.reflect.GenericDeclaration;
53 import java.lang.reflect.InvocationTargetException;
54 import java.lang.reflect.Member;
55 import java.lang.reflect.Method;
56 import java.lang.reflect.Modifier;
57 import java.lang.reflect.Type;
58 import java.lang.reflect.TypeVariable;
60 import java.security.AccessController;
61 import java.security.AllPermission;
62 import java.security.Permissions;
63 import java.security.PrivilegedAction;
64 import java.security.ProtectionDomain;
65 import java.util.ArrayList;
66 import java.util.Arrays;
67 import java.util.Collection;
68 import java.util.HashMap;
69 import java.util.HashSet;
73 * A Class represents a Java type. There will never be multiple Class
74 * objects with identical names and ClassLoaders. Primitive types, array
75 * types, and void also have a Class object.
77 * <p>Arrays with identical type and number of dimensions share the same class.
78 * The array class ClassLoader is the same as the ClassLoader of the element
79 * type of the array (which can be null to indicate the bootstrap classloader).
80 * The name of an array class is <code>[<signature format>;</code>.
82 * String[]'s class is <code>[Ljava.lang.String;</code>. boolean, byte,
83 * short, char, int, long, float and double have the "type name" of
84 * Z,B,S,C,I,J,F,D for the purposes of array classes. If it's a
85 * multidimensioned array, the same principle applies:
86 * <code>int[][][]</code> == <code>[[[I</code>.
88 * <p>There is no public constructor - Class objects are obtained only through
89 * the virtual machine, as defined in ClassLoaders.
91 * @serialData Class objects serialize specially:
92 * <code>TC_CLASS ClassDescriptor</code>. For more serialization information,
93 * see {@link ObjectStreamClass}.
96 * @author Eric Blake (ebb9@email.byu.edu)
97 * @author Tom Tromey (tromey@redhat.com)
98 * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
102 public final class Class<T>
103 implements Serializable, Type, AnnotatedElement, GenericDeclaration
106 * Compatible with JDK 1.0+.
108 private static final long serialVersionUID = 3206093459760846163L;
111 * Flag indicating a synthetic member.
112 * Note that this duplicates a constant in Modifier.
114 private static final int SYNTHETIC = 0x1000;
117 * Flag indiciating an annotation class.
119 private static final int ANNOTATION = 0x2000;
122 * Flag indicating an enum constant or an enum class.
123 * Note that this duplicates a constant in Modifier.
125 private static final int ENUM = 0x4000;
127 /** The class signers. */
128 private Object[] signers = null;
129 /** The class protection domain. */
130 private final transient ProtectionDomain pd;
132 /* We use an inner class, so that Class doesn't have a static initializer */
133 private static final class StaticData
135 static final ProtectionDomain unknownProtectionDomain;
139 Permissions permissions = new Permissions();
140 permissions.add(new AllPermission());
141 unknownProtectionDomain = new ProtectionDomain(null, permissions);
145 final transient Object vmdata;
147 /** newInstance() caches the default constructor */
148 private transient Constructor<T> constructor;
151 * Class is non-instantiable from Java code; only the VM can create
152 * instances of this class.
159 Class(Object vmdata, ProtectionDomain pd)
161 this.vmdata = vmdata;
162 // If the VM didn't supply a protection domain and the class is an array,
163 // we "inherit" the protection domain from the component type class. This
164 // saves the VM from having to worry about protection domains for array
166 if (pd == null && isArray())
167 this.pd = getComponentType().pd;
173 * Use the classloader of the current class to load, link, and initialize
174 * a class. This is equivalent to your code calling
175 * <code>Class.forName(name, true, getClass().getClassLoader())</code>.
177 * @param name the name of the class to find
178 * @return the Class object representing the class
179 * @throws ClassNotFoundException if the class was not found by the
181 * @throws LinkageError if linking the class fails
182 * @throws ExceptionInInitializerError if the class loads, but an exception
183 * occurs during initialization
185 public static Class<?> forName(String name) throws ClassNotFoundException
187 return VMClass.forName(name, true, VMStackWalker.getCallingClassLoader());
191 * Use the specified classloader to load and link a class. If the loader
192 * is null, this uses the bootstrap class loader (provide the security
193 * check succeeds). Unfortunately, this method cannot be used to obtain
194 * the Class objects for primitive types or for void, you have to use
195 * the fields in the appropriate java.lang wrapper classes.
197 * <p>Calls <code>classloader.loadclass(name, initialize)</code>.
199 * @param name the name of the class to find
200 * @param initialize whether or not to initialize the class at this time
201 * @param classloader the classloader to use to find the class; null means
202 * to use the bootstrap class loader
204 * @return the class object for the given class
206 * @throws ClassNotFoundException if the class was not found by the
208 * @throws LinkageError if linking the class fails
209 * @throws ExceptionInInitializerError if the class loads, but an exception
210 * occurs during initialization
211 * @throws SecurityException if the <code>classloader</code> argument
212 * is <code>null</code> and the caller does not have the
213 * <code>RuntimePermission("getClassLoader")</code> permission
217 public static Class<?> forName(String name, boolean initialize,
218 ClassLoader classloader)
219 throws ClassNotFoundException
221 if (classloader == null)
223 // Check if we may access the bootstrap classloader
224 SecurityManager sm = SecurityManager.current;
227 // Get the calling classloader
228 ClassLoader cl = VMStackWalker.getCallingClassLoader();
230 sm.checkPermission(new RuntimePermission("getClassLoader"));
233 return (Class<?>) VMClass.forName(name, initialize, classloader);
237 * Get all the public member classes and interfaces declared in this
238 * class or inherited from superclasses. This returns an array of length
239 * 0 if there are no member classes, including for primitive types. A
240 * security check may be performed, with
241 * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
242 * <code>checkPackageAccess</code> both having to succeed.
244 * @return all public member classes in this class
245 * @throws SecurityException if the security check fails
248 public Class<?>[] getClasses()
250 memberAccessCheck(Member.PUBLIC);
251 return internalGetClasses();
255 * Like <code>getClasses()</code> but without the security checks.
257 private Class<?>[] internalGetClasses()
259 ArrayList<Class> list = new ArrayList<Class>();
260 list.addAll(Arrays.asList(getDeclaredClasses(true)));
261 Class superClass = getSuperclass();
262 if (superClass != null)
263 list.addAll(Arrays.asList(superClass.internalGetClasses()));
264 return list.toArray(new Class<?>[list.size()]);
268 * Get the ClassLoader that loaded this class. If the class was loaded
269 * by the bootstrap classloader, this method will return null.
270 * If there is a security manager, and the caller's class loader is not
271 * an ancestor of the requested one, a security check of
272 * <code>RuntimePermission("getClassLoader")</code>
273 * must first succeed. Primitive types and void return null.
275 * @return the ClassLoader that loaded this class
276 * @throws SecurityException if the security check fails
278 * @see RuntimePermission
280 public ClassLoader getClassLoader()
285 ClassLoader loader = VMClass.getClassLoader(this);
286 // Check if we may get the classloader
287 SecurityManager sm = SecurityManager.current;
288 if (loader != null && sm != null)
290 // Get the calling classloader
291 ClassLoader cl = VMStackWalker.getCallingClassLoader();
292 if (cl != null && !cl.isAncestorOf(loader))
293 sm.checkPermission(new RuntimePermission("getClassLoader"));
299 * If this is an array, get the Class representing the type of array.
300 * Examples: "[[Ljava.lang.String;" would return "[Ljava.lang.String;", and
301 * calling getComponentType on that would give "java.lang.String". If
302 * this is not an array, returns null.
304 * @return the array type of this class, or null
308 public Class<?> getComponentType()
310 return VMClass.getComponentType (this);
314 * Get a public constructor declared in this class. If the constructor takes
315 * no argument, an array of zero elements and null are equivalent for the
316 * types argument. A security check may be performed, with
317 * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
318 * <code>checkPackageAccess</code> both having to succeed.
320 * @param types the type of each parameter
321 * @return the constructor
322 * @throws NoSuchMethodException if the constructor does not exist
323 * @throws SecurityException if the security check fails
324 * @see #getConstructors()
327 public Constructor<T> getConstructor(Class<?>... types)
328 throws NoSuchMethodException
330 memberAccessCheck(Member.PUBLIC);
331 Constructor[] constructors = getDeclaredConstructors(true);
332 for (int i = 0; i < constructors.length; i++)
334 Constructor constructor = constructors[i];
335 if (matchParameters(types, constructor.getParameterTypes()))
338 throw new NoSuchMethodException();
342 * Get all the public constructors of this class. This returns an array of
343 * length 0 if there are no constructors, including for primitive types,
344 * arrays, and interfaces. It does, however, include the default
345 * constructor if one was supplied by the compiler. A security check may
346 * be performed, with <code>checkMemberAccess(this, Member.PUBLIC)</code>
347 * as well as <code>checkPackageAccess</code> both having to succeed.
349 * @return all public constructors in this class
350 * @throws SecurityException if the security check fails
353 public Constructor<?>[] getConstructors()
355 memberAccessCheck(Member.PUBLIC);
356 return getDeclaredConstructors(true);
360 * Get a constructor declared in this class. If the constructor takes no
361 * argument, an array of zero elements and null are equivalent for the
362 * types argument. A security check may be performed, with
363 * <code>checkMemberAccess(this, Member.DECLARED)</code> as well as
364 * <code>checkPackageAccess</code> both having to succeed.
366 * @param types the type of each parameter
367 * @return the constructor
368 * @throws NoSuchMethodException if the constructor does not exist
369 * @throws SecurityException if the security check fails
370 * @see #getDeclaredConstructors()
373 public Constructor<T> getDeclaredConstructor(Class<?>... types)
374 throws NoSuchMethodException
376 memberAccessCheck(Member.DECLARED);
377 Constructor[] constructors = getDeclaredConstructors(false);
378 for (int i = 0; i < constructors.length; i++)
380 Constructor constructor = constructors[i];
381 if (matchParameters(types, constructor.getParameterTypes()))
384 throw new NoSuchMethodException();
388 * Get all the declared member classes and interfaces in this class, but
389 * not those inherited from superclasses. This returns an array of length
390 * 0 if there are no member classes, including for primitive types. A
391 * security check may be performed, with
392 * <code>checkMemberAccess(this, Member.DECLARED)</code> as well as
393 * <code>checkPackageAccess</code> both having to succeed.
395 * @return all declared member classes in this class
396 * @throws SecurityException if the security check fails
399 public Class<?>[] getDeclaredClasses()
401 memberAccessCheck(Member.DECLARED);
402 return getDeclaredClasses(false);
405 Class<?>[] getDeclaredClasses (boolean publicOnly)
407 return VMClass.getDeclaredClasses (this, publicOnly);
411 * Get all the declared constructors of this class. This returns an array of
412 * length 0 if there are no constructors, including for primitive types,
413 * arrays, and interfaces. It does, however, include the default
414 * constructor if one was supplied by the compiler. A security check may
415 * be performed, with <code>checkMemberAccess(this, Member.DECLARED)</code>
416 * as well as <code>checkPackageAccess</code> both having to succeed.
418 * @return all constructors in this class
419 * @throws SecurityException if the security check fails
422 public Constructor<?>[] getDeclaredConstructors()
424 memberAccessCheck(Member.DECLARED);
425 return getDeclaredConstructors(false);
428 Constructor<?>[] getDeclaredConstructors (boolean publicOnly)
430 return VMClass.getDeclaredConstructors (this, publicOnly);
434 * Get a field declared in this class, where name is its simple name. The
435 * implicit length field of arrays is not available. A security check may
436 * be performed, with <code>checkMemberAccess(this, Member.DECLARED)</code>
437 * as well as <code>checkPackageAccess</code> both having to succeed.
439 * @param name the name of the field
441 * @throws NoSuchFieldException if the field does not exist
442 * @throws SecurityException if the security check fails
443 * @see #getDeclaredFields()
446 public Field getDeclaredField(String name) throws NoSuchFieldException
448 memberAccessCheck(Member.DECLARED);
449 Field[] fields = getDeclaredFields(false);
450 for (int i = 0; i < fields.length; i++)
452 if (fields[i].getName().equals(name))
455 throw new NoSuchFieldException();
459 * Get all the declared fields in this class, but not those inherited from
460 * superclasses. This returns an array of length 0 if there are no fields,
461 * including for primitive types. This does not return the implicit length
462 * field of arrays. A security check may be performed, with
463 * <code>checkMemberAccess(this, Member.DECLARED)</code> as well as
464 * <code>checkPackageAccess</code> both having to succeed.
466 * @return all declared fields in this class
467 * @throws SecurityException if the security check fails
470 public Field[] getDeclaredFields()
472 memberAccessCheck(Member.DECLARED);
473 return getDeclaredFields(false);
476 Field[] getDeclaredFields (boolean publicOnly)
478 return VMClass.getDeclaredFields (this, publicOnly);
482 * Get a method declared in this class, where name is its simple name. The
483 * implicit methods of Object are not available from arrays or interfaces.
484 * Constructors (named "<init>" in the class file) and class initializers
485 * (name "<clinit>") are not available. The Virtual Machine allows
486 * multiple methods with the same signature but differing return types; in
487 * such a case the most specific return types are favored, then the final
488 * choice is arbitrary. If the method takes no argument, an array of zero
489 * elements and null are equivalent for the types argument. A security
490 * check may be performed, with
491 * <code>checkMemberAccess(this, Member.DECLARED)</code> as well as
492 * <code>checkPackageAccess</code> both having to succeed.
494 * @param methodName the name of the method
495 * @param types the type of each parameter
497 * @throws NoSuchMethodException if the method does not exist
498 * @throws SecurityException if the security check fails
499 * @see #getDeclaredMethods()
502 public Method getDeclaredMethod(String methodName, Class<?>... types)
503 throws NoSuchMethodException
505 memberAccessCheck(Member.DECLARED);
506 Method match = matchMethod(getDeclaredMethods(false), methodName, types);
508 throw new NoSuchMethodException(methodName);
513 * Get all the declared methods in this class, but not those inherited from
514 * superclasses. This returns an array of length 0 if there are no methods,
515 * including for primitive types. This does include the implicit methods of
516 * arrays and interfaces which mirror methods of Object, nor does it
517 * include constructors or the class initialization methods. The Virtual
518 * Machine allows multiple methods with the same signature but differing
519 * return types; all such methods are in the returned array. A security
520 * check may be performed, with
521 * <code>checkMemberAccess(this, Member.DECLARED)</code> as well as
522 * <code>checkPackageAccess</code> both having to succeed.
524 * @return all declared methods in this class
525 * @throws SecurityException if the security check fails
528 public Method[] getDeclaredMethods()
530 memberAccessCheck(Member.DECLARED);
531 return getDeclaredMethods(false);
534 Method[] getDeclaredMethods (boolean publicOnly)
536 return VMClass.getDeclaredMethods (this, publicOnly);
540 * If this is a nested or inner class, return the class that declared it.
541 * If not, return null.
543 * @return the declaring class of this class
546 public Class<?> getDeclaringClass()
548 return VMClass.getDeclaringClass (this);
552 * Get a public field declared or inherited in this class, where name is
553 * its simple name. If the class contains multiple accessible fields by
554 * that name, an arbitrary one is returned. The implicit length field of
555 * arrays is not available. A security check may be performed, with
556 * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
557 * <code>checkPackageAccess</code> both having to succeed.
559 * @param fieldName the name of the field
561 * @throws NoSuchFieldException if the field does not exist
562 * @throws SecurityException if the security check fails
566 public Field getField(String fieldName)
567 throws NoSuchFieldException
569 memberAccessCheck(Member.PUBLIC);
570 Field field = internalGetField(fieldName);
572 throw new NoSuchFieldException(fieldName);
577 * Get all the public fields declared in this class or inherited from
578 * superclasses. This returns an array of length 0 if there are no fields,
579 * including for primitive types. This does not return the implicit length
580 * field of arrays. A security check may be performed, with
581 * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
582 * <code>checkPackageAccess</code> both having to succeed.
584 * @return all public fields in this class
585 * @throws SecurityException if the security check fails
588 public Field[] getFields()
590 memberAccessCheck(Member.PUBLIC);
591 return internalGetFields();
595 * Like <code>getFields()</code> but without the security checks.
597 private Field[] internalGetFields()
599 HashSet<Field> set = new HashSet<Field>();
600 set.addAll(Arrays.asList(getDeclaredFields(true)));
601 Class[] interfaces = getInterfaces();
602 for (int i = 0; i < interfaces.length; i++)
603 set.addAll(Arrays.asList(interfaces[i].internalGetFields()));
604 Class superClass = getSuperclass();
605 if (superClass != null)
606 set.addAll(Arrays.asList(superClass.internalGetFields()));
607 return set.toArray(new Field[set.size()]);
611 * Returns the <code>Package</code> in which this class is defined
612 * Returns null when this information is not available from the
613 * classloader of this class.
615 * @return the package for this class, if it is available
618 public Package getPackage()
620 ClassLoader cl = getClassLoader();
622 return cl.getPackage(getPackagePortion(getName()));
624 return VMClassLoader.getPackage(getPackagePortion(getName()));
628 * Get the interfaces this class <em>directly</em> implements, in the
629 * order that they were declared. This returns an empty array, not null,
630 * for Object, primitives, void, and classes or interfaces with no direct
631 * superinterface. Array types return Cloneable and Serializable.
633 * @return the interfaces this class directly implements
635 public Class<?>[] getInterfaces()
637 return VMClass.getInterfaces (this);
640 private static final class MethodKey
643 private Class[] params;
644 private Class returnType;
650 params = m.getParameterTypes();
651 returnType = m.getReturnType();
652 hash = name.hashCode() ^ returnType.hashCode();
653 for(int i = 0; i < params.length; i++)
655 hash ^= params[i].hashCode();
659 public boolean equals(Object o)
661 if (o instanceof MethodKey)
663 MethodKey m = (MethodKey) o;
664 if (m.name.equals(name) && m.params.length == params.length
665 && m.returnType == returnType)
667 for (int i = 0; i < params.length; i++)
669 if (m.params[i] != params[i])
678 public int hashCode()
685 * Get a public method declared or inherited in this class, where name is
686 * its simple name. The implicit methods of Object are not available from
687 * interfaces. Constructors (named "<init>" in the class file) and class
688 * initializers (name "<clinit>") are not available. The Virtual
689 * Machine allows multiple methods with the same signature but differing
690 * return types, and the class can inherit multiple methods of the same
691 * return type; in such a case the most specific return types are favored,
692 * then the final choice is arbitrary. If the method takes no argument, an
693 * array of zero elements and null are equivalent for the types argument.
694 * A security check may be performed, with
695 * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
696 * <code>checkPackageAccess</code> both having to succeed.
698 * @param methodName the name of the method
699 * @param types the type of each parameter
701 * @throws NoSuchMethodException if the method does not exist
702 * @throws SecurityException if the security check fails
706 public Method getMethod(String methodName, Class<?>... types)
707 throws NoSuchMethodException
709 memberAccessCheck(Member.PUBLIC);
710 Method method = internalGetMethod(methodName, types);
712 throw new NoSuchMethodException(methodName);
717 * Like <code>getMethod(String,Class[])</code> but without the security
718 * checks and returns null instead of throwing NoSuchMethodException.
720 private Method internalGetMethod(String methodName, Class[] args)
722 Method match = matchMethod(getDeclaredMethods(true), methodName, args);
725 Class superClass = getSuperclass();
726 if (superClass != null)
728 match = superClass.internalGetMethod(methodName, args);
732 Class[] interfaces = getInterfaces();
733 for (int i = 0; i < interfaces.length; i++)
735 match = interfaces[i].internalGetMethod(methodName, args);
743 * Find the best matching method in <code>list</code> according to
744 * the definition of ``best matching'' used by <code>getMethod()</code>
747 * Returns the method if any, otherwise <code>null</code>.
749 * @param list List of methods to search
750 * @param name Name of method
751 * @param args Method parameter types
752 * @see #getMethod(String, Class[])
754 private static Method matchMethod(Method[] list, String name, Class[] args)
757 for (int i = 0; i < list.length; i++)
759 Method method = list[i];
760 if (!method.getName().equals(name))
762 if (!matchParameters(args, method.getParameterTypes()))
765 || match.getReturnType().isAssignableFrom(method.getReturnType()))
772 * Check for an exact match between parameter type lists.
773 * Either list may be <code>null</code> to mean a list of
776 private static boolean matchParameters(Class[] types1, Class[] types2)
779 return types2 == null || types2.length == 0;
781 return types1 == null || types1.length == 0;
782 if (types1.length != types2.length)
784 for (int i = 0; i < types1.length; i++)
786 if (types1[i] != types2[i])
793 * Get all the public methods declared in this class or inherited from
794 * superclasses. This returns an array of length 0 if there are no methods,
795 * including for primitive types. This does not include the implicit
796 * methods of interfaces which mirror methods of Object, nor does it
797 * include constructors or the class initialization methods. The Virtual
798 * Machine allows multiple methods with the same signature but differing
799 * return types; all such methods are in the returned array. A security
800 * check may be performed, with
801 * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
802 * <code>checkPackageAccess</code> both having to succeed.
804 * @return all public methods in this class
805 * @throws SecurityException if the security check fails
808 public Method[] getMethods()
810 memberAccessCheck(Member.PUBLIC);
811 // NOTE the API docs claim that no methods are returned for arrays,
812 // but Sun's implementation *does* return the public methods of Object
813 // (as would be expected), so we follow their implementation instead
814 // of their documentation.
815 return internalGetMethods();
819 * Like <code>getMethods()</code> but without the security checks.
821 private Method[] internalGetMethods()
823 HashMap<MethodKey,Method> map = new HashMap<MethodKey,Method>();
825 Class[] interfaces = getInterfaces();
826 for(int i = 0; i < interfaces.length; i++)
828 methods = interfaces[i].internalGetMethods();
829 for(int j = 0; j < methods.length; j++)
831 map.put(new MethodKey(methods[j]), methods[j]);
834 Class superClass = getSuperclass();
835 if(superClass != null)
837 methods = superClass.internalGetMethods();
838 for(int i = 0; i < methods.length; i++)
840 map.put(new MethodKey(methods[i]), methods[i]);
843 methods = getDeclaredMethods(true);
844 for(int i = 0; i < methods.length; i++)
846 map.put(new MethodKey(methods[i]), methods[i]);
848 return map.values().toArray(new Method[map.size()]);
852 * Get the modifiers of this class. These can be decoded using Modifier,
853 * and is limited to one of public, protected, or private, and any of
854 * final, static, abstract, or interface. An array class has the same
855 * public, protected, or private modifier as its component type, and is
856 * marked final but not an interface. Primitive types and void are marked
857 * public and final, but not an interface.
859 * @return the modifiers of this class
863 public int getModifiers()
865 int mod = VMClass.getModifiers (this, false);
866 return (mod & (Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE |
867 Modifier.FINAL | Modifier.STATIC | Modifier.ABSTRACT |
868 Modifier.INTERFACE));
872 * Get the name of this class, separated by dots for package separators.
873 * If the class represents a primitive type, or void, then the
874 * name of the type as it appears in the Java programming language
875 * is returned. For instance, <code>Byte.TYPE.getName()</code>
878 * Arrays are specially encoded as shown on this table.
880 * array type [<em>element type</em>
881 * (note that the element type is encoded per
892 * class or interface, alone: <dotted name>
893 * class or interface, as element type: L<dotted name>;
896 * @return the name of this class
898 public String getName()
900 return VMClass.getName (this);
904 * Get a resource URL using this class's package using the
905 * getClassLoader().getResource() method. If this class was loaded using
906 * the system classloader, ClassLoader.getSystemResource() is used instead.
908 * <p>If the name you supply is absolute (it starts with a <code>/</code>),
909 * then the leading <code>/</code> is removed and it is passed on to
910 * getResource(). If it is relative, the package name is prepended, and
911 * <code>.</code>'s are replaced with <code>/</code>.
913 * <p>The URL returned is system- and classloader-dependent, and could
914 * change across implementations.
916 * @param resourceName the name of the resource, generally a path
917 * @return the URL to the resource
918 * @throws NullPointerException if name is null
921 public URL getResource(String resourceName)
923 String name = resourcePath(resourceName);
924 ClassLoader loader = getClassLoader();
926 return ClassLoader.getSystemResource(name);
927 return loader.getResource(name);
931 * Get a resource using this class's package using the
932 * getClassLoader().getResourceAsStream() method. If this class was loaded
933 * using the system classloader, ClassLoader.getSystemResource() is used
936 * <p>If the name you supply is absolute (it starts with a <code>/</code>),
937 * then the leading <code>/</code> is removed and it is passed on to
938 * getResource(). If it is relative, the package name is prepended, and
939 * <code>.</code>'s are replaced with <code>/</code>.
941 * <p>The URL returned is system- and classloader-dependent, and could
942 * change across implementations.
944 * @param resourceName the name of the resource, generally a path
945 * @return an InputStream with the contents of the resource in it, or null
946 * @throws NullPointerException if name is null
949 public InputStream getResourceAsStream(String resourceName)
951 String name = resourcePath(resourceName);
952 ClassLoader loader = getClassLoader();
954 return ClassLoader.getSystemResourceAsStream(name);
955 return loader.getResourceAsStream(name);
958 private String resourcePath(String resourceName)
960 if (resourceName.length() > 0)
962 if (resourceName.charAt(0) != '/')
964 String pkg = getPackagePortion(getName());
965 if (pkg.length() > 0)
966 resourceName = pkg.replace('.','/') + '/' + resourceName;
970 resourceName = resourceName.substring(1);
977 * Get the signers of this class. This returns null if there are no signers,
978 * such as for primitive types or void.
980 * @return the signers of this class
983 public Object[] getSigners()
985 return signers == null ? null : (Object[]) signers.clone ();
989 * Set the signers of this class.
991 * @param signers the signers of this class
993 void setSigners(Object[] signers)
995 this.signers = signers;
999 * Get the direct superclass of this class. If this is an interface,
1000 * Object, a primitive type, or void, it will return null. If this is an
1001 * array type, it will return Object.
1003 * @return the direct superclass of this class
1005 public Class<? super T> getSuperclass()
1007 return VMClass.getSuperclass (this);
1011 * Return whether this class is an array type.
1013 * @return whether this class is an array type
1016 public boolean isArray()
1018 return VMClass.isArray (this);
1022 * Discover whether an instance of the Class parameter would be an
1023 * instance of this Class as well. Think of doing
1024 * <code>isInstance(c.newInstance())</code> or even
1025 * <code>c.newInstance() instanceof (this class)</code>. While this
1026 * checks widening conversions for objects, it must be exact for primitive
1029 * @param c the class to check
1030 * @return whether an instance of c would be an instance of this class
1032 * @throws NullPointerException if c is null
1035 public boolean isAssignableFrom(Class<?> c)
1037 return VMClass.isAssignableFrom (this, c);
1041 * Discover whether an Object is an instance of this Class. Think of it
1042 * as almost like <code>o instanceof (this class)</code>.
1044 * @param o the Object to check
1045 * @return whether o is an instance of this class
1048 public boolean isInstance(Object o)
1050 return VMClass.isInstance (this, o);
1054 * Check whether this class is an interface or not. Array types are not
1057 * @return whether this class is an interface or not
1059 public boolean isInterface()
1061 return VMClass.isInterface (this);
1065 * Return whether this class is a primitive type. A primitive type class
1066 * is a class representing a kind of "placeholder" for the various
1067 * primitive types, or void. You can access the various primitive type
1068 * classes through java.lang.Boolean.TYPE, java.lang.Integer.TYPE, etc.,
1069 * or through boolean.class, int.class, etc.
1071 * @return whether this class is a primitive type
1074 * @see Character#TYPE
1083 public boolean isPrimitive()
1085 return VMClass.isPrimitive (this);
1089 * Get a new instance of this class by calling the no-argument constructor.
1090 * The class is initialized if it has not been already. A security check
1091 * may be performed, with <code>checkMemberAccess(this, Member.PUBLIC)</code>
1092 * as well as <code>checkPackageAccess</code> both having to succeed.
1094 * @return a new instance of this class
1095 * @throws InstantiationException if there is not a no-arg constructor
1096 * for this class, including interfaces, abstract classes, arrays,
1097 * primitive types, and void; or if an exception occurred during
1099 * @throws IllegalAccessException if you are not allowed to access the
1100 * no-arg constructor because of scoping reasons
1101 * @throws SecurityException if the security check fails
1102 * @throws ExceptionInInitializerError if class initialization caused by
1103 * this call fails with an exception
1105 public T newInstance()
1106 throws InstantiationException, IllegalAccessException
1108 memberAccessCheck(Member.PUBLIC);
1109 Constructor<T> constructor;
1112 constructor = this.constructor;
1114 if (constructor == null)
1116 Constructor[] constructors = getDeclaredConstructors(false);
1117 for (int i = 0; i < constructors.length; i++)
1119 if (constructors[i].getParameterTypes().length == 0)
1121 constructor = constructors[i];
1125 if (constructor == null)
1126 throw new InstantiationException(getName());
1127 if (!Modifier.isPublic(constructor.getModifiers())
1128 || !Modifier.isPublic(VMClass.getModifiers(this, true)))
1130 setAccessible(constructor);
1134 if (this.constructor == null)
1135 this.constructor = constructor;
1138 int modifiers = constructor.getModifiers();
1139 if (!Modifier.isPublic(modifiers)
1140 || !Modifier.isPublic(VMClass.getModifiers(this, true)))
1142 Class caller = VMStackWalker.getCallingClass();
1143 if (caller != null &&
1145 (Modifier.isPrivate(modifiers)
1146 || getClassLoader() != caller.getClassLoader()
1147 || !getPackagePortion(getName())
1148 .equals(getPackagePortion(caller.getName()))))
1149 throw new IllegalAccessException(getName()
1150 + " has an inaccessible constructor");
1154 return constructor.newInstance(null);
1156 catch (InvocationTargetException e)
1158 VMClass.throwException(e.getTargetException());
1159 throw (InternalError) new InternalError
1160 ("VMClass.throwException returned").initCause(e);
1165 * Returns the protection domain of this class. If the classloader did not
1166 * record the protection domain when creating this class the unknown
1167 * protection domain is returned which has a <code>null</code> code source
1168 * and all permissions. A security check may be performed, with
1169 * <code>RuntimePermission("getProtectionDomain")</code>.
1171 * @return the protection domain
1172 * @throws SecurityException if the security manager exists and the caller
1173 * does not have <code>RuntimePermission("getProtectionDomain")</code>.
1174 * @see RuntimePermission
1177 public ProtectionDomain getProtectionDomain()
1179 SecurityManager sm = SecurityManager.current;
1181 sm.checkPermission(new RuntimePermission("getProtectionDomain"));
1183 return pd == null ? StaticData.unknownProtectionDomain : pd;
1187 * Return the human-readable form of this Object. For an object, this
1188 * is either "interface " or "class " followed by <code>getName()</code>,
1189 * for primitive types and void it is just <code>getName()</code>.
1191 * @return the human-readable form of this Object
1193 public String toString()
1197 return (isInterface() ? "interface " : "class ") + getName();
1201 * Returns the desired assertion status of this class, if it were to be
1202 * initialized at this moment. The class assertion status, if set, is
1203 * returned; the backup is the default package status; then if there is
1204 * a class loader, that default is returned; and finally the system default
1205 * is returned. This method seldom needs calling in user code, but exists
1206 * for compilers to implement the assert statement. Note that there is no
1207 * guarantee that the result of this method matches the class's actual
1210 * @return the desired assertion status
1211 * @see ClassLoader#setClassAssertionStatus(String, boolean)
1212 * @see ClassLoader#setPackageAssertionStatus(String, boolean)
1213 * @see ClassLoader#setDefaultAssertionStatus(boolean)
1216 public boolean desiredAssertionStatus()
1218 ClassLoader c = getClassLoader();
1221 return VMClassLoader.defaultAssertionStatus();
1222 if (c.classAssertionStatus != null)
1225 status = c.classAssertionStatus.get(getName());
1227 return status.equals(Boolean.TRUE);
1231 status = ClassLoader.StaticData.
1232 systemClassAssertionStatus.get(getName());
1234 return status.equals(Boolean.TRUE);
1236 if (c.packageAssertionStatus != null)
1239 String name = getPackagePortion(getName());
1240 if ("".equals(name))
1241 status = c.packageAssertionStatus.get(null);
1245 status = c.packageAssertionStatus.get(name);
1246 name = getPackagePortion(name);
1248 while (! "".equals(name) && status == null);
1250 return status.equals(Boolean.TRUE);
1254 String name = getPackagePortion(getName());
1255 if ("".equals(name))
1256 status = ClassLoader.StaticData.
1257 systemPackageAssertionStatus.get(null);
1261 status = ClassLoader.StaticData.
1262 systemPackageAssertionStatus.get(name);
1263 name = getPackagePortion(name);
1265 while (! "".equals(name) && status == null);
1267 return status.equals(Boolean.TRUE);
1269 return c.defaultAssertionStatus;
1274 * Casts this class to represent a subclass of the specified class.
1275 * This method is useful for `narrowing' the type of a class so that
1276 * the class object, and instances of that class, can match the contract
1277 * of a more restrictive method. For example, if this class has the
1278 * static type of <code>Class<Object></code>, and a dynamic type of
1279 * <code>Class<Rectangle></code>, then, assuming <code>Shape</code> is
1280 * a superclass of <code>Rectangle</code>, this method can be used on
1281 * this class with the parameter, <code>Class<Shape></code>, to retain
1282 * the same instance but with the type
1283 * <code>Class<? extends Shape></code>.
1286 * If this class can be converted to an instance which is parameterised
1287 * over a subtype of the supplied type, <code>U</code>, then this method
1288 * returns an appropriately cast reference to this object. Otherwise,
1289 * a <code>ClassCastException</code> is thrown.
1292 * @param klass the class object, the parameterized type (<code>U</code>) of
1293 * which should be a superclass of the parameterized type of
1295 * @return a reference to this object, appropriately cast.
1296 * @throws ClassCastException if this class can not be converted to one
1297 * which represents a subclass of the specified
1298 * type, <code>U</code>.
1301 public <U> Class<? extends U> asSubclass(Class<U> klass)
1303 if (! klass.isAssignableFrom(this))
1304 throw new ClassCastException();
1305 return (Class<? extends U>) this;
1309 * Returns the specified object, cast to this <code>Class</code>' type.
1311 * @param obj the object to cast
1312 * @throws ClassCastException if obj is not an instance of this class
1315 public T cast(Object obj)
1317 if (obj != null && ! isInstance(obj))
1318 throw new ClassCastException();
1323 * Like <code>getField(String)</code> but without the security checks and
1324 * returns null instead of throwing NoSuchFieldException.
1326 private Field internalGetField(String name)
1328 Field[] fields = getDeclaredFields(true);
1329 for (int i = 0; i < fields.length; i++)
1331 Field field = fields[i];
1332 if (field.getName().equals(name))
1335 Class[] interfaces = getInterfaces();
1336 for (int i = 0; i < interfaces.length; i++)
1338 Field field = interfaces[i].internalGetField(name);
1342 Class superClass = getSuperclass();
1343 if (superClass != null)
1344 return superClass.internalGetField(name);
1349 * Strip the last portion of the name (after the last dot).
1351 * @param name the name to get package of
1352 * @return the package name, or "" if no package
1354 private static String getPackagePortion(String name)
1356 int lastInd = name.lastIndexOf('.');
1359 return name.substring(0, lastInd);
1363 * Perform security checks common to all of the methods that
1364 * get members of this Class.
1366 private void memberAccessCheck(int which)
1368 SecurityManager sm = SecurityManager.current;
1371 sm.checkMemberAccess(this, which);
1372 Package pkg = getPackage();
1374 sm.checkPackageAccess(pkg.getName());
1379 * Returns the enumeration constants of this class, or
1380 * null if this class is not an <code>Enum</code>.
1382 * @return an array of <code>Enum</code> constants
1383 * associated with this class, or null if this
1384 * class is not an <code>enum</code>.
1387 public T[] getEnumConstants()
1393 Method m = getMethod("values");
1395 return (T[]) m.invoke(null);
1397 catch (NoSuchMethodException exception)
1399 throw new Error("Enum lacks values() method");
1401 catch (IllegalAccessException exception)
1403 throw new Error("Unable to access Enum class");
1405 catch (InvocationTargetException exception)
1408 RuntimeException("The values method threw an exception",
1419 * Returns true if this class is an <code>Enum</code>.
1421 * @return true if this is an enumeration class.
1424 public boolean isEnum()
1426 int mod = VMClass.getModifiers (this, true);
1427 return (mod & ENUM) != 0;
1431 * Returns true if this class is a synthetic class, generated by
1434 * @return true if this is a synthetic class.
1437 public boolean isSynthetic()
1439 int mod = VMClass.getModifiers (this, true);
1440 return (mod & SYNTHETIC) != 0;
1444 * Returns true if this class is an <code>Annotation</code>.
1446 * @return true if this is an annotation class.
1449 public boolean isAnnotation()
1451 int mod = VMClass.getModifiers (this, true);
1452 return (mod & ANNOTATION) != 0;
1456 * Returns the simple name for this class, as used in the source
1457 * code. For normal classes, this is the content returned by
1458 * <code>getName()</code> which follows the last ".". Anonymous
1459 * classes have no name, and so the result of calling this method is
1460 * "". The simple name of an array consists of the simple name of
1461 * its component type, followed by "[]". Thus, an array with the
1462 * component type of an anonymous class has a simple name of simply
1465 * @return the simple name for this class.
1468 public String getSimpleName()
1470 return VMClass.getSimpleName(this);
1474 * Returns this class' annotation for the specified annotation type,
1475 * or <code>null</code> if no such annotation exists.
1477 * @param annotationClass the type of annotation to look for.
1478 * @return this class' annotation for the specified type, or
1479 * <code>null</code> if no such annotation exists.
1482 public <A extends Annotation> A getAnnotation(Class<A> annotationClass)
1484 A foundAnnotation = null;
1485 Annotation[] annotations = getAnnotations();
1486 for (Annotation annotation : annotations)
1487 if (annotation.annotationType() == annotationClass)
1488 foundAnnotation = (A) annotation;
1489 return foundAnnotation;
1493 * Returns all annotations associated with this class. If there are
1494 * no annotations associated with this class, then a zero-length array
1495 * will be returned. The returned array may be modified by the client
1496 * code, but this will have no effect on the annotation content of this
1497 * class, and hence no effect on the return value of this method for
1500 * @return this class' annotations.
1503 public Annotation[] getAnnotations()
1505 HashMap<Class, Annotation> map = new HashMap<Class, Annotation>();
1506 for (Annotation a : getDeclaredAnnotations())
1507 map.put((Class) a.annotationType(), a);
1508 for (Class<? super T> s = getSuperclass();
1510 s = s.getSuperclass())
1512 for (Annotation a : s.getDeclaredAnnotations())
1514 Class k = (Class) a.annotationType();
1515 if (! map.containsKey(k) && k.isAnnotationPresent(Inherited.class))
1519 Collection<Annotation> v = map.values();
1520 return v.toArray(new Annotation[v.size()]);
1525 * Returns the canonical name of this class, as defined by section
1526 * 6.7 of the Java language specification. Each package, top-level class,
1527 * top-level interface and primitive type has a canonical name. A member
1528 * class has a canonical name, if its parent class has one. Likewise,
1529 * an array type has a canonical name, if its component type does.
1530 * Local or anonymous classes do not have canonical names.
1533 * The canonical name for top-level classes, top-level interfaces and
1534 * primitive types is always the same as the fully-qualified name.
1535 * For array types, the canonical name is the canonical name of its
1536 * component type with `[]' appended.
1539 * The canonical name of a member class always refers to the place where
1540 * the class was defined, and is composed of the canonical name of the
1541 * defining class and the simple name of the member class, joined by `.'.
1542 * For example, if a <code>Person</code> class has an inner class,
1543 * <code>M</code>, then both its fully-qualified name and canonical name
1544 * is <code>Person.M</code>. A subclass, <code>Staff</code>, of
1545 * <code>Person</code> refers to the same inner class by the fully-qualified
1546 * name of <code>Staff.M</code>, but its canonical name is still
1547 * <code>Person.M</code>.
1550 * Where no canonical name is present, <code>null</code> is returned.
1553 * @return the canonical name of the class, or <code>null</code> if the
1554 * class doesn't have a canonical name.
1557 public String getCanonicalName()
1559 return VMClass.getCanonicalName(this);
1563 * Returns all annotations directly defined by this class. If there are
1564 * no annotations associated with this class, then a zero-length array
1565 * will be returned. The returned array may be modified by the client
1566 * code, but this will have no effect on the annotation content of this
1567 * class, and hence no effect on the return value of this method for
1570 * @return the annotations directly defined by this class.
1573 public Annotation[] getDeclaredAnnotations()
1575 return VMClass.getDeclaredAnnotations(this);
1579 * Returns the class which immediately encloses this class. If this class
1580 * is a top-level class, this method returns <code>null</code>.
1582 * @return the immediate enclosing class, or <code>null</code> if this is
1583 * a top-level class.
1586 public Class<?> getEnclosingClass()
1588 return VMClass.getEnclosingClass(this);
1592 * Returns the constructor which immediately encloses this class. If
1593 * this class is a top-level class, or a local or anonymous class
1594 * immediately enclosed by a type definition, instance initializer
1595 * or static initializer, then <code>null</code> is returned.
1597 * @return the immediate enclosing constructor if this class is
1598 * declared within a constructor. Otherwise, <code>null</code>
1602 public Constructor<?> getEnclosingConstructor()
1604 return VMClass.getEnclosingConstructor(this);
1608 * Returns the method which immediately encloses this class. If
1609 * this class is a top-level class, or a local or anonymous class
1610 * immediately enclosed by a type definition, instance initializer
1611 * or static initializer, then <code>null</code> is returned.
1613 * @return the immediate enclosing method if this class is
1614 * declared within a method. Otherwise, <code>null</code>
1618 public Method getEnclosingMethod()
1620 return VMClass.getEnclosingMethod(this);
1625 * Returns an array of <code>Type</code> objects which represent the
1626 * interfaces directly implemented by this class or extended by this
1630 * If one of the superinterfaces is a parameterized type, then the
1631 * object returned for this interface reflects the actual type
1632 * parameters used in the source code. Type parameters are created
1633 * using the semantics specified by the <code>ParameterizedType</code>
1634 * interface, and only if an instance has not already been created.
1637 * The order of the interfaces in the array matches the order in which
1638 * the interfaces are declared. For classes which represent an array,
1639 * an array of two interfaces, <code>Cloneable</code> and
1640 * <code>Serializable</code>, is always returned, with the objects in
1641 * that order. A class representing a primitive type or void always
1642 * returns an array of zero size.
1645 * @return an array of interfaces implemented or extended by this class.
1646 * @throws GenericSignatureFormatError if the generic signature of one
1647 * of the interfaces does not comply with that specified by the Java
1648 * Virtual Machine specification, 3rd edition.
1649 * @throws TypeNotPresentException if any of the superinterfaces refers
1650 * to a non-existant type.
1651 * @throws MalformedParameterizedTypeException if any of the interfaces
1652 * refer to a parameterized type that can not be instantiated for
1655 * @see java.lang.reflect.ParameterizedType
1657 public Type[] getGenericInterfaces()
1662 String sig = VMClass.getClassSignature(this);
1664 return getInterfaces();
1666 ClassSignatureParser p = new ClassSignatureParser(this, sig);
1667 return p.getInterfaceTypes();
1672 * Returns a <code>Type</code> object representing the direct superclass,
1673 * whether class, interface, primitive type or void, of this class.
1674 * If this class is an array class, then a class instance representing
1675 * the <code>Object</code> class is returned. If this class is primitive,
1676 * an interface, or a representation of either the <code>Object</code>
1677 * class or void, then <code>null</code> is returned.
1680 * If the superclass is a parameterized type, then the
1681 * object returned for this interface reflects the actual type
1682 * parameters used in the source code. Type parameters are created
1683 * using the semantics specified by the <code>ParameterizedType</code>
1684 * interface, and only if an instance has not already been created.
1687 * @return the superclass of this class.
1688 * @throws GenericSignatureFormatError if the generic signature of the
1689 * class does not comply with that specified by the Java
1690 * Virtual Machine specification, 3rd edition.
1691 * @throws TypeNotPresentException if the superclass refers
1692 * to a non-existant type.
1693 * @throws MalformedParameterizedTypeException if the superclass
1694 * refers to a parameterized type that can not be instantiated for
1697 * @see java.lang.reflect.ParameterizedType
1699 public Type getGenericSuperclass()
1702 return Object.class;
1704 if (isPrimitive() || isInterface() || this == Object.class)
1707 String sig = VMClass.getClassSignature(this);
1709 return getSuperclass();
1711 ClassSignatureParser p = new ClassSignatureParser(this, sig);
1712 return p.getSuperclassType();
1716 * Returns an array of <code>TypeVariable</code> objects that represents
1717 * the type variables declared by this class, in declaration order.
1718 * An array of size zero is returned if this class has no type
1721 * @return the type variables associated with this class.
1722 * @throws GenericSignatureFormatError if the generic signature does
1723 * not conform to the format specified in the Virtual Machine
1724 * specification, version 3.
1727 public TypeVariable<Class<T>>[] getTypeParameters()
1729 String sig = VMClass.getClassSignature(this);
1731 return (TypeVariable<Class<T>>[])new TypeVariable[0];
1733 ClassSignatureParser p = new ClassSignatureParser(this, sig);
1734 return p.getTypeParameters();
1738 * Returns true if an annotation for the specified type is associated
1739 * with this class. This is primarily a short-hand for using marker
1742 * @param annotationClass the type of annotation to look for.
1743 * @return true if an annotation exists for the specified type.
1746 public boolean isAnnotationPresent(Class<? extends Annotation>
1749 return getAnnotation(annotationClass) != null;
1753 * Returns true if this object represents an anonymous class.
1755 * @return true if this object represents an anonymous class.
1758 public boolean isAnonymousClass()
1760 return VMClass.isAnonymousClass(this);
1764 * Returns true if this object represents an local class.
1766 * @return true if this object represents an local class.
1769 public boolean isLocalClass()
1771 return VMClass.isLocalClass(this);
1775 * Returns true if this object represents an member class.
1777 * @return true if this object represents an member class.
1780 public boolean isMemberClass()
1782 return VMClass.isMemberClass(this);
1786 * Utility method for use by classes in this package.
1788 static void setAccessible(final AccessibleObject obj)
1790 AccessController.doPrivileged(new PrivilegedAction()
1794 obj.setAccessible(true);