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
.java
.lang
.reflect
.ClassSignatureParser
;
42 import java
.io
.InputStream
;
43 import java
.io
.Serializable
;
44 import java
.lang
.annotation
.Annotation
;
45 import java
.lang
.reflect
.Constructor
;
46 import java
.lang
.reflect
.Field
;
47 import java
.lang
.reflect
.GenericDeclaration
;
48 import java
.lang
.reflect
.InvocationTargetException
;
49 import java
.lang
.reflect
.Member
;
50 import java
.lang
.reflect
.Method
;
51 import java
.lang
.reflect
.Type
;
52 import java
.lang
.reflect
.TypeVariable
;
54 import java
.security
.ProtectionDomain
;
55 import java
.util
.ArrayList
;
56 import java
.util
.Arrays
;
57 import java
.util
.HashSet
;
58 import java
.util
.HashMap
;
59 import java
.util
.Collection
;
60 import java
.lang
.reflect
.AnnotatedElement
;
61 import java
.lang
.annotation
.Annotation
;
62 import java
.lang
.annotation
.Inherited
;
65 * A Class represents a Java type. There will never be multiple Class
66 * objects with identical names and ClassLoaders. Primitive types, array
67 * types, and void also have a Class object.
69 * <p>Arrays with identical type and number of dimensions share the same class.
70 * The array class ClassLoader is the same as the ClassLoader of the element
71 * type of the array (which can be null to indicate the bootstrap classloader).
72 * The name of an array class is <code>[<signature format>;</code>.
74 * String[]'s class is <code>[Ljava.lang.String;</code>. boolean, byte,
75 * short, char, int, long, float and double have the "type name" of
76 * Z,B,S,C,I,J,F,D for the purposes of array classes. If it's a
77 * multidimensioned array, the same principle applies:
78 * <code>int[][][]</code> == <code>[[[I</code>.
80 * <p>There is no public constructor - Class objects are obtained only through
81 * the virtual machine, as defined in ClassLoaders.
83 * @serialData Class objects serialize specially:
84 * <code>TC_CLASS ClassDescriptor</code>. For more serialization information,
85 * see {@link ObjectStreamClass}.
88 * @author Eric Blake (ebb9@email.byu.edu)
89 * @author Tom Tromey (tromey@cygnus.com)
93 public final class Class
<T
>
94 implements Type
, AnnotatedElement
, GenericDeclaration
, Serializable
97 * Class is non-instantiable from Java code; only the VM can create
98 * instances of this class.
104 // Initialize the class.
105 private native void initializeClass ();
108 protected native void finalize () throws Throwable
;
111 * Use the classloader of the current class to load, link, and initialize
112 * a class. This is equivalent to your code calling
113 * <code>Class.forName(name, true, getClass().getClassLoader())</code>.
115 * @param name the name of the class to find
116 * @return the Class object representing the class
117 * @throws ClassNotFoundException if the class was not found by the
119 * @throws LinkageError if linking the class fails
120 * @throws ExceptionInInitializerError if the class loads, but an exception
121 * occurs during initialization
123 public static native Class
<?
> forName (String className
)
124 throws ClassNotFoundException
;
126 // A private internal method that is called by compiler-generated code.
127 private static Class
forName (String className
, Class caller
)
128 throws ClassNotFoundException
130 return forName(className
, true, caller
.getClassLoaderInternal());
135 * Use the specified classloader to load and link a class. If the loader
136 * is null, this uses the bootstrap class loader (provide the security
137 * check succeeds). Unfortunately, this method cannot be used to obtain
138 * the Class objects for primitive types or for void, you have to use
139 * the fields in the appropriate java.lang wrapper classes.
141 * <p>Calls <code>classloader.loadclass(name, initialize)</code>.
143 * @param name the name of the class to find
144 * @param initialize whether or not to initialize the class at this time
145 * @param classloader the classloader to use to find the class; null means
146 * to use the bootstrap class loader
147 * @throws ClassNotFoundException if the class was not found by the
149 * @throws LinkageError if linking the class fails
150 * @throws ExceptionInInitializerError if the class loads, but an exception
151 * occurs during initialization
152 * @throws SecurityException if the <code>classloader</code> argument
153 * is <code>null</code> and the caller does not have the
154 * <code>RuntimePermission("getClassLoader")</code> permission
158 public static native Class
<?
> forName (String className
, boolean initialize
,
160 throws ClassNotFoundException
;
163 * Get all the public member classes and interfaces declared in this
164 * class or inherited from superclasses. This returns an array of length
165 * 0 if there are no member classes, including for primitive types. A
166 * security check may be performed, with
167 * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
168 * <code>checkPackageAccess</code> both having to succeed.
170 * @return all public member classes in this class
171 * @throws SecurityException if the security check fails
174 public Class
<?
>[] getClasses()
176 memberAccessCheck(Member
.PUBLIC
);
177 return internalGetClasses();
181 * Like <code>getClasses()</code> but without the security checks.
183 private Class
<?
>[] internalGetClasses()
185 ArrayList
<Class
> list
= new ArrayList
<Class
>();
186 list
.addAll(Arrays
.asList(getDeclaredClasses(true)));
187 Class superClass
= getSuperclass();
188 if (superClass
!= null)
189 list
.addAll(Arrays
.asList(superClass
.internalGetClasses()));
190 return list
.toArray(new Class
<?
>[list
.size()]);
194 * Get the ClassLoader that loaded this class. If the class was loaded
195 * by the bootstrap classloader, this method will return null.
196 * If there is a security manager, and the caller's class loader is not
197 * an ancestor of the requested one, a security check of
198 * <code>RuntimePermission("getClassLoader")</code>
199 * must first succeed. Primitive types and void return null.
201 * @return the ClassLoader that loaded this class
202 * @throws SecurityException if the security check fails
204 * @see RuntimePermission
206 public native ClassLoader
getClassLoader ();
208 // A private internal method that is called by compiler-generated code.
209 private final native ClassLoader
getClassLoader (Class caller
);
212 * Internal method that circumvents the usual security checks when
213 * getting the class loader.
215 private native ClassLoader
getClassLoaderInternal ();
218 * If this is an array, get the Class representing the type of array.
219 * Examples: "[[Ljava.lang.String;" would return "[Ljava.lang.String;", and
220 * calling getComponentType on that would give "java.lang.String". If
221 * this is not an array, returns null.
223 * @return the array type of this class, or null
227 public native Class
<?
> getComponentType ();
230 * Get a public constructor declared in this class. If the constructor takes
231 * no argument, an array of zero elements and null are equivalent for the
232 * types argument. A security check may be performed, with
233 * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
234 * <code>checkPackageAccess</code> both having to succeed.
236 * @param types the type of each parameter
237 * @return the constructor
238 * @throws NoSuchMethodException if the constructor does not exist
239 * @throws SecurityException if the security check fails
240 * @see #getConstructors()
243 public native Constructor
<T
> getConstructor(Class
<?
>... args
)
244 throws NoSuchMethodException
;
247 * Get all the public constructors of this class. This returns an array of
248 * length 0 if there are no constructors, including for primitive types,
249 * arrays, and interfaces. It does, however, include the default
250 * constructor if one was supplied by the compiler. A security check may
251 * be performed, with <code>checkMemberAccess(this, Member.PUBLIC)</code>
252 * as well as <code>checkPackageAccess</code> both having to succeed.
254 * @return all public constructors in this class
255 * @throws SecurityException if the security check fails
258 public Constructor
<?
>[] getConstructors()
260 memberAccessCheck(Member
.PUBLIC
);
261 return getDeclaredConstructors(true);
265 * Get a constructor declared in this class. If the constructor takes no
266 * argument, an array of zero elements and null are equivalent for the
267 * types argument. A security check may be performed, with
268 * <code>checkMemberAccess(this, Member.DECLARED)</code> as well as
269 * <code>checkPackageAccess</code> both having to succeed.
271 * @param types the type of each parameter
272 * @return the constructor
273 * @throws NoSuchMethodException if the constructor does not exist
274 * @throws SecurityException if the security check fails
275 * @see #getDeclaredConstructors()
278 public native Constructor
<T
> getDeclaredConstructor(Class
<?
>... args
)
279 throws NoSuchMethodException
;
282 * Get all the declared member classes and interfaces in this class, but
283 * not those inherited from superclasses. This returns an array of length
284 * 0 if there are no member classes, including for primitive types. A
285 * security check may be performed, with
286 * <code>checkMemberAccess(this, Member.DECLARED)</code> as well as
287 * <code>checkPackageAccess</code> both having to succeed.
289 * @return all declared member classes in this class
290 * @throws SecurityException if the security check fails
293 public Class
<?
>[] getDeclaredClasses()
295 memberAccessCheck(Member
.DECLARED
);
296 return getDeclaredClasses(false);
299 native Class
<?
>[] getDeclaredClasses (boolean publicOnly
);
302 * Get all the declared constructors of this class. This returns an array of
303 * length 0 if there are no constructors, including for primitive types,
304 * arrays, and interfaces. It does, however, include the default
305 * constructor if one was supplied by the compiler. A security check may
306 * be performed, with <code>checkMemberAccess(this, Member.DECLARED)</code>
307 * as well as <code>checkPackageAccess</code> both having to succeed.
309 * @return all constructors in this class
310 * @throws SecurityException if the security check fails
313 public Constructor
<?
>[] getDeclaredConstructors()
315 memberAccessCheck(Member
.DECLARED
);
316 return getDeclaredConstructors(false);
319 native Constructor
<?
>[] getDeclaredConstructors (boolean publicOnly
);
322 * Get a field declared in this class, where name is its simple name. The
323 * implicit length field of arrays is not available. A security check may
324 * be performed, with <code>checkMemberAccess(this, Member.DECLARED)</code>
325 * as well as <code>checkPackageAccess</code> both having to succeed.
327 * @param name the name of the field
329 * @throws NoSuchFieldException if the field does not exist
330 * @throws SecurityException if the security check fails
331 * @see #getDeclaredFields()
334 public native Field
getDeclaredField(String fieldName
)
335 throws NoSuchFieldException
;
338 * Get all the declared fields in this class, but not those inherited from
339 * superclasses. This returns an array of length 0 if there are no fields,
340 * including for primitive types. This does not return the implicit length
341 * field of arrays. A security check may be performed, with
342 * <code>checkMemberAccess(this, Member.DECLARED)</code> as well as
343 * <code>checkPackageAccess</code> both having to succeed.
345 * @return all declared fields in this class
346 * @throws SecurityException if the security check fails
349 public Field
[] getDeclaredFields()
351 memberAccessCheck(Member
.DECLARED
);
352 return getDeclaredFields(false);
355 native Field
[] getDeclaredFields (boolean publicOnly
);
357 private native Method
_getDeclaredMethod(String methodName
, Class
[] args
);
360 * Get a method declared in this class, where name is its simple name. The
361 * implicit methods of Object are not available from arrays or interfaces.
362 * Constructors (named "<init>" in the class file) and class initializers
363 * (name "<clinit>") are not available. The Virtual Machine allows
364 * multiple methods with the same signature but differing return types; in
365 * such a case the most specific return types are favored, then the final
366 * choice is arbitrary. If the method takes no argument, an array of zero
367 * elements and null are equivalent for the types argument. A security
368 * check may be performed, with
369 * <code>checkMemberAccess(this, Member.DECLARED)</code> as well as
370 * <code>checkPackageAccess</code> both having to succeed.
372 * @param methodName the name of the method
373 * @param types the type of each parameter
375 * @throws NoSuchMethodException if the method does not exist
376 * @throws SecurityException if the security check fails
377 * @see #getDeclaredMethods()
380 public Method
getDeclaredMethod(String methodName
, Class
<?
>... args
)
381 throws NoSuchMethodException
383 memberAccessCheck(Member
.DECLARED
);
385 if ("<init>".equals(methodName
) || "<clinit>".equals(methodName
))
386 throw new NoSuchMethodException(methodName
);
388 Method match
= _getDeclaredMethod(methodName
, args
);
390 throw new NoSuchMethodException(methodName
);
395 * Get all the declared methods in this class, but not those inherited from
396 * superclasses. This returns an array of length 0 if there are no methods,
397 * including for primitive types. This does include the implicit methods of
398 * arrays and interfaces which mirror methods of Object, nor does it
399 * include constructors or the class initialization methods. The Virtual
400 * Machine allows multiple methods with the same signature but differing
401 * return types; all such methods are in the returned array. A security
402 * check may be performed, with
403 * <code>checkMemberAccess(this, Member.DECLARED)</code> as well as
404 * <code>checkPackageAccess</code> both having to succeed.
406 * @return all declared methods in this class
407 * @throws SecurityException if the security check fails
410 public native Method
[] getDeclaredMethods();
413 * If this is a nested or inner class, return the class that declared it.
414 * If not, return null.
416 * @return the declaring class of this class
419 // This is marked as unimplemented in the JCL book.
420 public native Class
<?
> getDeclaringClass ();
422 private native Field
getField (String fieldName
, int hash
)
423 throws NoSuchFieldException
;
426 * Get a public field declared or inherited in this class, where name is
427 * its simple name. If the class contains multiple accessible fields by
428 * that name, an arbitrary one is returned. The implicit length field of
429 * arrays is not available. A security check may be performed, with
430 * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
431 * <code>checkPackageAccess</code> both having to succeed.
433 * @param fieldName the name of the field
435 * @throws NoSuchFieldException if the field does not exist
436 * @throws SecurityException if the security check fails
440 public Field
getField(String fieldName
)
441 throws NoSuchFieldException
443 memberAccessCheck(Member
.PUBLIC
);
444 Field field
= getField(fieldName
, fieldName
.hashCode());
446 throw new NoSuchFieldException(fieldName
);
451 * Get all the public fields declared in this class or inherited from
452 * superclasses. This returns an array of length 0 if there are no fields,
453 * including for primitive types. This does not return the implicit length
454 * field of arrays. A security check may be performed, with
455 * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
456 * <code>checkPackageAccess</code> both having to succeed.
458 * @return all public fields in this class
459 * @throws SecurityException if the security check fails
462 public Field
[] getFields()
464 memberAccessCheck(Member
.PUBLIC
);
465 return internalGetFields();
469 * Like <code>getFields()</code> but without the security checks.
471 private Field
[] internalGetFields()
473 HashSet set
= new HashSet();
474 set
.addAll(Arrays
.asList(getDeclaredFields(true)));
475 Class
[] interfaces
= getInterfaces();
476 for (int i
= 0; i
< interfaces
.length
; i
++)
477 set
.addAll(Arrays
.asList(interfaces
[i
].internalGetFields()));
478 Class superClass
= getSuperclass();
479 if (superClass
!= null)
480 set
.addAll(Arrays
.asList(superClass
.internalGetFields()));
481 return (Field
[])set
.toArray(new Field
[set
.size()]);
485 * Returns the <code>Package</code> in which this class is defined
486 * Returns null when this information is not available from the
487 * classloader of this class.
489 * @return the package for this class, if it is available
492 public Package
getPackage()
494 ClassLoader cl
= getClassLoaderInternal();
496 return cl
.getPackage(getPackagePortion(getName()));
498 return VMClassLoader
.getPackage(getPackagePortion(getName()));
502 * Get the interfaces this class <em>directly</em> implements, in the
503 * order that they were declared. This returns an empty array, not null,
504 * for Object, primitives, void, and classes or interfaces with no direct
505 * superinterface. Array types return Cloneable and Serializable.
507 * @return the interfaces this class directly implements
509 public native Class
<?
>[] getInterfaces ();
511 private final native void getSignature(StringBuffer buffer
);
512 private static final native String
getSignature(Class
[] args
,
513 boolean is_construtor
);
515 public native Method
_getMethod(String methodName
, Class
[] args
);
518 * Get a public method declared or inherited in this class, where name is
519 * its simple name. The implicit methods of Object are not available from
520 * interfaces. Constructors (named "<init>" in the class file) and class
521 * initializers (name "<clinit>") are not available. The Virtual
522 * Machine allows multiple methods with the same signature but differing
523 * return types, and the class can inherit multiple methods of the same
524 * return type; in such a case the most specific return types are favored,
525 * then the final choice is arbitrary. If the method takes no argument, an
526 * array of zero elements and null are equivalent for the types argument.
527 * A security check may be performed, with
528 * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
529 * <code>checkPackageAccess</code> both having to succeed.
531 * @param methodName the name of the method
532 * @param types the type of each parameter
534 * @throws NoSuchMethodException if the method does not exist
535 * @throws SecurityException if the security check fails
539 public Method
getMethod(String methodName
, Class
<?
>... args
)
540 throws NoSuchMethodException
542 memberAccessCheck(Member
.PUBLIC
);
544 if ("<init>".equals(methodName
) || "<clinit>".equals(methodName
))
545 throw new NoSuchMethodException(methodName
);
547 Method method
= _getMethod(methodName
, args
);
549 throw new NoSuchMethodException(methodName
);
553 private native int _getMethods (Method
[] result
, int offset
);
556 * Get all the public methods declared in this class or inherited from
557 * superclasses. This returns an array of length 0 if there are no methods,
558 * including for primitive types. This does not include the implicit
559 * methods of interfaces which mirror methods of Object, nor does it
560 * include constructors or the class initialization methods. The Virtual
561 * Machine allows multiple methods with the same signature but differing
562 * return types; all such methods are in the returned array. A security
563 * check may be performed, with
564 * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
565 * <code>checkPackageAccess</code> both having to succeed.
567 * @return all public methods in this class
568 * @throws SecurityException if the security check fails
571 public native Method
[] getMethods();
574 * Get the modifiers of this class. These can be decoded using Modifier,
575 * and is limited to one of public, protected, or private, and any of
576 * final, static, abstract, or interface. An array class has the same
577 * public, protected, or private modifier as its component type, and is
578 * marked final but not an interface. Primitive types and void are marked
579 * public and final, but not an interface.
581 * @return the modifiers of this class
585 public native int getModifiers ();
588 * Get the name of this class, separated by dots for package separators.
589 * If the class represents a primitive type, or void, then the
590 * name of the type as it appears in the Java programming language
591 * is returned. For instance, <code>Byte.TYPE.getName()</code>
594 * Arrays are specially encoded as shown on this table.
596 * array type [<em>element type</em>
597 * (note that the element type is encoded per
608 * class or interface, alone: <dotted name>
609 * class or interface, as element type: L<dotted name>;
612 * @return the name of this class
614 public native String
getName ();
617 * Get a resource URL using this class's package using the
618 * getClassLoader().getResource() method. If this class was loaded using
619 * the system classloader, ClassLoader.getSystemResource() is used instead.
621 * <p>If the name you supply is absolute (it starts with a <code>/</code>),
622 * then the leading <code>/</code> is removed and it is passed on to
623 * getResource(). If it is relative, the package name is prepended, and
624 * <code>.</code>'s are replaced with <code>/</code>.
626 * <p>The URL returned is system- and classloader-dependent, and could
627 * change across implementations.
629 * @param resourceName the name of the resource, generally a path
630 * @return the URL to the resource
631 * @throws NullPointerException if name is null
634 public URL
getResource(String resourceName
)
636 String name
= resourcePath(resourceName
);
637 ClassLoader loader
= getClassLoaderInternal();
639 return ClassLoader
.getSystemResource(name
);
640 return loader
.getResource(name
);
644 * Get a resource using this class's package using the
645 * getClassLoader().getResourceAsStream() method. If this class was loaded
646 * using the system classloader, ClassLoader.getSystemResource() is used
649 * <p>If the name you supply is absolute (it starts with a <code>/</code>),
650 * then the leading <code>/</code> is removed and it is passed on to
651 * getResource(). If it is relative, the package name is prepended, and
652 * <code>.</code>'s are replaced with <code>/</code>.
654 * <p>The URL returned is system- and classloader-dependent, and could
655 * change across implementations.
657 * @param resourceName the name of the resource, generally a path
658 * @return an InputStream with the contents of the resource in it, or null
659 * @throws NullPointerException if name is null
662 public InputStream
getResourceAsStream(String resourceName
)
664 String name
= resourcePath(resourceName
);
665 ClassLoader loader
= getClassLoaderInternal();
667 return ClassLoader
.getSystemResourceAsStream(name
);
668 return loader
.getResourceAsStream(name
);
671 private String
resourcePath(String resourceName
)
673 if (resourceName
.length() > 0)
675 if (resourceName
.charAt(0) != '/')
677 String pkg
= getPackagePortion(getName());
678 if (pkg
.length() > 0)
679 resourceName
= pkg
.replace('.','/') + '/' + resourceName
;
683 resourceName
= resourceName
.substring(1);
690 * Get the signers of this class. This returns null if there are no signers,
691 * such as for primitive types or void.
693 * @return the signers of this class
696 public native Object
[] getSigners ();
699 * Set the signers of this class.
701 * @param signers the signers of this class
703 native void setSigners(Object
[] signers
);
706 * Get the direct superclass of this class. If this is an interface,
707 * Object, a primitive type, or void, it will return null. If this is an
708 * array type, it will return Object.
710 * @return the direct superclass of this class
712 public native Class
<?
super T
> getSuperclass ();
715 * Return whether this class is an array type.
717 * @return whether this class is an array type
720 public native boolean isArray ();
723 * Discover whether an instance of the Class parameter would be an
724 * instance of this Class as well. Think of doing
725 * <code>isInstance(c.newInstance())</code> or even
726 * <code>c.newInstance() instanceof (this class)</code>. While this
727 * checks widening conversions for objects, it must be exact for primitive
730 * @param c the class to check
731 * @return whether an instance of c would be an instance of this class
733 * @throws NullPointerException if c is null
736 public native boolean isAssignableFrom (Class
<?
> c
);
739 * Discover whether an Object is an instance of this Class. Think of it
740 * as almost like <code>o instanceof (this class)</code>.
742 * @param o the Object to check
743 * @return whether o is an instance of this class
746 public native boolean isInstance (Object o
);
749 * Check whether this class is an interface or not. Array types are not
752 * @return whether this class is an interface or not
754 public native boolean isInterface ();
757 * Return whether this class is a primitive type. A primitive type class
758 * is a class representing a kind of "placeholder" for the various
759 * primitive types, or void. You can access the various primitive type
760 * classes through java.lang.Boolean.TYPE, java.lang.Integer.TYPE, etc.,
761 * or through boolean.class, int.class, etc.
763 * @return whether this class is a primitive type
766 * @see Character#TYPE
775 public native boolean isPrimitive ();
778 * Get a new instance of this class by calling the no-argument constructor.
779 * The class is initialized if it has not been already. A security check
780 * may be performed, with <code>checkMemberAccess(this, Member.PUBLIC)</code>
781 * as well as <code>checkPackageAccess</code> both having to succeed.
783 * @return a new instance of this class
784 * @throws InstantiationException if there is not a no-arg constructor
785 * for this class, including interfaces, abstract classes, arrays,
786 * primitive types, and void; or if an exception occurred during
788 * @throws IllegalAccessException if you are not allowed to access the
789 * no-arg constructor because of scoping reasons
790 * @throws SecurityException if the security check fails
791 * @throws ExceptionInInitializerError if class initialization caused by
792 * this call fails with an exception
794 public native T
newInstance ()
795 throws InstantiationException
, IllegalAccessException
;
797 // We need a native method to retrieve the protection domain, because we
798 // can't add fields to java.lang.Class that are accessible from Java.
799 private native ProtectionDomain
getProtectionDomain0();
802 * Returns the protection domain of this class. If the classloader did not
803 * record the protection domain when creating this class the unknown
804 * protection domain is returned which has a <code>null</code> code source
805 * and all permissions. A security check may be performed, with
806 * <code>RuntimePermission("getProtectionDomain")</code>.
808 * @return the protection domain
809 * @throws SecurityException if the security manager exists and the caller
810 * does not have <code>RuntimePermission("getProtectionDomain")</code>.
811 * @see RuntimePermission
814 public ProtectionDomain
getProtectionDomain()
816 SecurityManager sm
= System
.getSecurityManager();
818 sm
.checkPermission(VMClassLoader
.protectionDomainPermission
);
820 ProtectionDomain protectionDomain
= getProtectionDomain0();
822 if (protectionDomain
== null)
823 return VMClassLoader
.unknownProtectionDomain
;
825 return protectionDomain
;
829 * Return the human-readable form of this Object. For an object, this
830 * is either "interface " or "class " followed by <code>getName()</code>,
831 * for primitive types and void it is just <code>getName()</code>.
833 * @return the human-readable form of this Object
835 public String
toString()
839 return (isInterface() ?
"interface " : "class ") + getName();
843 * Returns the desired assertion status of this class, if it were to be
844 * initialized at this moment. The class assertion status, if set, is
845 * returned; the backup is the default package status; then if there is
846 * a class loader, that default is returned; and finally the system default
847 * is returned. This method seldom needs calling in user code, but exists
848 * for compilers to implement the assert statement. Note that there is no
849 * guarantee that the result of this method matches the class's actual
852 * @return the desired assertion status
853 * @see ClassLoader#setClassAssertionStatus(String, boolean)
854 * @see ClassLoader#setPackageAssertionStatus(String, boolean)
855 * @see ClassLoader#setDefaultAssertionStatus(boolean)
858 public boolean desiredAssertionStatus()
860 ClassLoader c
= getClassLoaderInternal();
863 return VMClassLoader
.defaultAssertionStatus();
864 if (c
.classAssertionStatus
!= null)
867 status
= c
.classAssertionStatus
.get(getName());
869 return status
.equals(Boolean
.TRUE
);
873 status
= ClassLoader
.systemClassAssertionStatus
.get(getName());
875 return status
.equals(Boolean
.TRUE
);
877 if (c
.packageAssertionStatus
!= null)
880 String name
= getPackagePortion(getName());
882 status
= c
.packageAssertionStatus
.get(null);
886 status
= c
.packageAssertionStatus
.get(name
);
887 name
= getPackagePortion(name
);
889 while (! "".equals(name
) && status
== null);
891 return status
.equals(Boolean
.TRUE
);
895 String name
= getPackagePortion(getName());
897 status
= ClassLoader
.systemPackageAssertionStatus
.get(null);
901 status
= ClassLoader
.systemPackageAssertionStatus
.get(name
);
902 name
= getPackagePortion(name
);
904 while (! "".equals(name
) && status
== null);
906 return status
.equals(Boolean
.TRUE
);
908 return c
.defaultAssertionStatus
;
912 * Strip the last portion of the name (after the last dot).
914 * @param name the name to get package of
915 * @return the package name, or "" if no package
917 private static String
getPackagePortion(String name
)
919 int lastInd
= name
.lastIndexOf('.');
922 return name
.substring(0, lastInd
);
926 * Perform security checks common to all of the methods that
927 * get members of this Class.
929 private void memberAccessCheck(int which
)
931 SecurityManager sm
= System
.getSecurityManager();
934 sm
.checkMemberAccess(this, which
);
935 Package pkg
= getPackage();
937 sm
.checkPackageAccess(pkg
.getName());
944 * Casts this class to represent a subclass of the specified class.
945 * This method is useful for `narrowing' the type of a class so that
946 * the class object, and instances of that class, can match the contract
947 * of a more restrictive method. For example, if this class has the
948 * static type of <code>Class<Object></code>, and a dynamic type of
949 * <code>Class<Rectangle></code>, then, assuming <code>Shape</code> is
950 * a superclass of <code>Rectangle</code>, this method can be used on
951 * this class with the parameter, <code>Class<Shape></code>, to retain
952 * the same instance but with the type
953 * <code>Class<? extends Shape></code>.
956 * If this class can be converted to an instance which is parameterised
957 * over a subtype of the supplied type, <code>U</code>, then this method
958 * returns an appropriately cast reference to this object. Otherwise,
959 * a <code>ClassCastException</code> is thrown.
962 * @param klass the class object, the parameterized type (<code>U</code>) of
963 * which should be a superclass of the parameterized type of
965 * @return a reference to this object, appropriately cast.
966 * @throws ClassCastException if this class can not be converted to one
967 * which represents a subclass of the specified
968 * type, <code>U</code>.
971 public <U
> Class
<?
extends U
> asSubclass(Class
<U
> klass
)
973 if (! klass
.isAssignableFrom(this))
974 throw new ClassCastException();
975 return (Class
<?
extends U
>) this;
979 * Returns the specified object, cast to this <code>Class</code>' type.
981 * @param obj the object to cast
982 * @throws ClassCastException if obj is not an instance of this class
985 public T
cast(Object obj
)
987 if (obj
!= null && ! isInstance(obj
))
988 throw new ClassCastException();
993 * Returns the enumeration constants of this class, or
994 * null if this class is not an <code>Enum</code>.
996 * @return an array of <code>Enum</code> constants
997 * associated with this class, or null if this
998 * class is not an <code>enum</code>.
1001 public T
[] getEnumConstants()
1007 return (T
[]) getMethod("values").invoke(null);
1009 catch (NoSuchMethodException exception
)
1011 throw new Error("Enum lacks values() method");
1013 catch (IllegalAccessException exception
)
1015 throw new Error("Unable to access Enum class");
1017 catch (InvocationTargetException exception
)
1020 RuntimeException("The values method threw an exception",
1031 * Returns true if this class is an <code>Enum</code>.
1033 * @return true if this is an enumeration class.
1036 public native boolean isEnum();
1040 * Returns true if this class is a synthetic class, generated by
1043 * @return true if this is a synthetic class.
1046 public native boolean isSynthetic();
1050 * Returns true if this class is an <code>Annotation</code>.
1052 * @return true if this is an annotation class.
1055 public native boolean isAnnotation();
1059 * Returns the simple name for this class, as used in the source
1060 * code. For normal classes, this is the content returned by
1061 * <code>getName()</code> which follows the last ".". Anonymous
1062 * classes have no name, and so the result of calling this method is
1063 * "". The simple name of an array consists of the simple name of
1064 * its component type, followed by "[]". Thus, an array with the
1065 * component type of an anonymous class has a simple name of simply
1068 * @return the simple name for this class.
1071 public String
getSimpleName()
1073 StringBuffer sb
= new StringBuffer();
1076 while (klass
.isArray())
1078 klass
= klass
.getComponentType();
1081 if (! klass
.isAnonymousClass())
1083 String fullName
= klass
.getName();
1084 sb
.append(fullName
, fullName
.lastIndexOf(".") + 1, fullName
.length());
1086 while (arrayCount
-- > 0)
1088 return sb
.toString();
1092 * Returns the class which immediately encloses this class. If this class
1093 * is a top-level class, this method returns <code>null</code>.
1095 * @return the immediate enclosing class, or <code>null</code> if this is
1096 * a top-level class.
1099 public native Class
<?
> getEnclosingClass();
1102 * Returns the constructor which immediately encloses this class. If
1103 * this class is a top-level class, or a local or anonymous class
1104 * immediately enclosed by a type definition, instance initializer
1105 * or static initializer, then <code>null</code> is returned.
1107 * @return the immediate enclosing constructor if this class is
1108 * declared within a constructor. Otherwise, <code>null</code>
1112 public native Constructor
<T
> getEnclosingConstructor();
1115 * Returns the method which immediately encloses this class. If
1116 * this class is a top-level class, or a local or anonymous class
1117 * immediately enclosed by a type definition, instance initializer
1118 * or static initializer, then <code>null</code> is returned.
1120 * @return the immediate enclosing method if this class is
1121 * declared within a method. Otherwise, <code>null</code>
1125 public native Method
getEnclosingMethod();
1127 private native String
getClassSignature();
1131 * Returns an array of <code>Type</code> objects which represent the
1132 * interfaces directly implemented by this class or extended by this
1136 * If one of the superinterfaces is a parameterized type, then the
1137 * object returned for this interface reflects the actual type
1138 * parameters used in the source code. Type parameters are created
1139 * using the semantics specified by the <code>ParameterizedType</code>
1140 * interface, and only if an instance has not already been created.
1143 * The order of the interfaces in the array matches the order in which
1144 * the interfaces are declared. For classes which represent an array,
1145 * an array of two interfaces, <code>Cloneable</code> and
1146 * <code>Serializable</code>, is always returned, with the objects in
1147 * that order. A class representing a primitive type or void always
1148 * returns an array of zero size.
1151 * @return an array of interfaces implemented or extended by this class.
1152 * @throws GenericSignatureFormatError if the generic signature of one
1153 * of the interfaces does not comply with that specified by the Java
1154 * Virtual Machine specification, 3rd edition.
1155 * @throws TypeNotPresentException if any of the superinterfaces refers
1156 * to a non-existant type.
1157 * @throws MalformedParameterizedTypeException if any of the interfaces
1158 * refer to a parameterized type that can not be instantiated for
1161 * @see java.lang.reflect.ParameterizedType
1163 public Type
[] getGenericInterfaces()
1168 String sig
= getClassSignature();
1170 return getInterfaces();
1172 ClassSignatureParser p
= new ClassSignatureParser(this, sig
);
1173 return p
.getInterfaceTypes();
1178 * Returns a <code>Type</code> object representing the direct superclass,
1179 * whether class, interface, primitive type or void, of this class.
1180 * If this class is an array class, then a class instance representing
1181 * the <code>Object</code> class is returned. If this class is primitive,
1182 * an interface, or a representation of either the <code>Object</code>
1183 * class or void, then <code>null</code> is returned.
1186 * If the superclass is a parameterized type, then the
1187 * object returned for this interface reflects the actual type
1188 * parameters used in the source code. Type parameters are created
1189 * using the semantics specified by the <code>ParameterizedType</code>
1190 * interface, and only if an instance has not already been created.
1193 * @return the superclass of this class.
1194 * @throws GenericSignatureFormatError if the generic signature of the
1195 * class does not comply with that specified by the Java
1196 * Virtual Machine specification, 3rd edition.
1197 * @throws TypeNotPresentException if the superclass refers
1198 * to a non-existant type.
1199 * @throws MalformedParameterizedTypeException if the superclass
1200 * refers to a parameterized type that can not be instantiated for
1203 * @see java.lang.reflect.ParameterizedType
1205 public Type
getGenericSuperclass()
1208 return Object
.class;
1210 if (isPrimitive() || isInterface() || this == Object
.class)
1213 String sig
= getClassSignature();
1215 return getSuperclass();
1217 ClassSignatureParser p
= new ClassSignatureParser(this, sig
);
1218 return p
.getSuperclassType();
1222 * Returns an array of <code>TypeVariable</code> objects that represents
1223 * the type variables declared by this class, in declaration order.
1224 * An array of size zero is returned if this class has no type
1227 * @return the type variables associated with this class.
1228 * @throws GenericSignatureFormatError if the generic signature does
1229 * not conform to the format specified in the Virtual Machine
1230 * specification, version 3.
1233 public TypeVariable
<Class
<T
>>[] getTypeParameters()
1235 String sig
= getClassSignature();
1237 return (TypeVariable
<Class
<T
>>[])new TypeVariable
[0];
1239 ClassSignatureParser p
= new ClassSignatureParser(this, sig
);
1240 return p
.getTypeParameters();
1244 * Returns this class' annotation for the specified annotation type,
1245 * or <code>null</code> if no such annotation exists.
1247 * @param annotationClass the type of annotation to look for.
1248 * @return this class' annotation for the specified type, or
1249 * <code>null</code> if no such annotation exists.
1252 public <A
extends Annotation
> A
getAnnotation(Class
<A
> annotationClass
)
1254 A foundAnnotation
= null;
1255 Annotation
[] annotations
= getAnnotations();
1256 for (Annotation annotation
: annotations
)
1257 if (annotation
.annotationType() == annotationClass
)
1258 foundAnnotation
= (A
) annotation
;
1259 return foundAnnotation
;
1263 * Returns all annotations associated with this class. If there are
1264 * no annotations associated with this class, then a zero-length array
1265 * will be returned. The returned array may be modified by the client
1266 * code, but this will have no effect on the annotation content of this
1267 * class, and hence no effect on the return value of this method for
1270 * @return this class' annotations.
1273 public Annotation
[] getAnnotations()
1275 HashMap
<Class
, Annotation
> map
= new HashMap
<Class
, Annotation
>();
1276 for (Annotation a
: getDeclaredAnnotations())
1277 map
.put((Class
) a
.annotationType(), a
);
1278 for (Class
<?
super T
> s
= getSuperclass();
1280 s
= s
.getSuperclass())
1282 for (Annotation a
: s
.getDeclaredAnnotations())
1284 Class k
= (Class
) a
.annotationType();
1285 if (! map
.containsKey(k
) && k
.isAnnotationPresent(Inherited
.class))
1289 Collection
<Annotation
> v
= map
.values();
1290 return v
.toArray(new Annotation
[v
.size()]);
1294 * Returns all annotations directly defined by this class. If there are
1295 * no annotations associated with this class, then a zero-length array
1296 * will be returned. The returned array may be modified by the client
1297 * code, but this will have no effect on the annotation content of this
1298 * class, and hence no effect on the return value of this method for
1301 * @return the annotations directly defined by this class.
1304 public Annotation
[] getDeclaredAnnotations()
1306 Annotation
[] result
= getDeclaredAnnotationsInternal();
1308 result
= new Annotation
[0];
1312 private native Annotation
[] getDeclaredAnnotationsInternal();
1315 * Returns true if an annotation for the specified type is associated
1316 * with this class. This is primarily a short-hand for using marker
1319 * @param annotationClass the type of annotation to look for.
1320 * @return true if an annotation exists for the specified type.
1323 public boolean isAnnotationPresent(Class
<?
extends Annotation
>
1326 return getAnnotation(annotationClass
) != null;
1330 * Returns true if this object represents an anonymous class.
1332 * @return true if this object represents an anonymous class.
1335 public native boolean isAnonymousClass();
1338 * Returns true if this object represents an local class.
1340 * @return true if this object represents an local class.
1343 public native boolean isLocalClass();
1346 * Returns true if this object represents an member class.
1348 * @return true if this object represents an member class.
1351 public native boolean isMemberClass();