T
- the type of the class modeled by this Class
object. For example, the type of
String.class
is Class<String>
. Use Class<?>
if the class being
modeled is unknown.public final class Class<T> extends Object implements AnnotatedElement, GenericDeclaration, Serializable, Type
Class
represent classes and interfaces in a running Java
application. An enum is a kind of class and an annotation is a kind of interface. Every array
also belongs to a class that is reflected as a Class
object that is shared by all arrays
with the same element type and number of dimensions. The primitive Java types (boolean
,
byte
, char
, short
, int
, long
, float
, and
double
), and the keyword void
are also represented as Class
objects.
Class
has no public constructor. Instead Class
objects are constructed
automatically by the Java Virtual Machine as classes are loaded.
The following example uses a Class
object to print the class name of an object:
void printClassName(Object obj) { System.out.println("The class of " + obj + " is " + obj.getClass().getName()); }
It is also possible to get the Class
object for a named type (or for void) using a class
literal. See Section 15.8.2 of The Java™ Language Specification. For example:
System.out.println("The name of class Foo is: "+Foo.class.getName());
Modifier and Type | Method and Description |
---|---|
<U> Class<? extends U> |
asSubclass(Class<U> clazz)
Casts this
Class object to represent a subclass of the class
represented by the specified class object. |
T |
cast(Object obj)
Casts an object to the class or interface represented by this
Class object. |
boolean |
desiredAssertionStatus()
Returns the assertion status that would be assigned to this class if it were to be initialized at
the time this method is invoked.
|
static Class<?> |
forName(String className)
Returns the
Class object associated with the class or interface with the given string
name. |
String |
getName()
Returns the name of the entity (class, interface, array class, primitive type, or void)
represented by this
Class object, as a String . |
Package |
getPackage()
Gets the package for this class.
|
InputStream |
getResourceAsStream(String name)
Finds a resource with a given name.
|
String |
getSimpleName()
Returns the simple name of the underlying class as given in the source code.
|
Class<? super T> |
getSuperclass()
Returns the
Class representing the superclass of the entity (class, interface, primitive
type or void) represented by this Class . |
boolean |
isArray()
Determines if this
Class object represents an array class. |
boolean |
isAssignableFrom(Class<?> cls)
Determines if the class or interface represented by this
Class object is either the same
as, or is a superclass or superinterface of, the class or interface represented by the specified
Class parameter. |
boolean |
isInstance(Object obj)
Determines if the specified
Object is assignment-compatible with the object represented
by this Class . |
boolean |
isInterface()
Determines if the specified
Class object represents an interface type. |
T |
newInstance()
Creates a new instance of the class represented by this
Class object. |
String |
toString()
Converts the object to a string.
|
public <U> Class<? extends U> asSubclass(Class<U> clazz)
Class
object to represent a subclass of the class
represented by the specified class object. Checks that the cast is valid, and
throws a ClassCastException
if it is not. If this method succeeds, it
always returns a reference to this class object.
This method is useful when a client needs to "narrow" the type of a
Class
object to pass it to an API that restricts the Class
objects that it is willing to accept. A cast would generate a compile-time
warning, as the correctness of the cast could not be checked at runtime
(because generic types are implemented by erasure).
U
- the type to cast this class object toclazz
- the class of the type to cast this class object to.Class
object, cast to represent a subclass of the
specified class object.ClassCastException
- if this Class
object does not represent a subclass of the
specified class (here "subclass" includes the class itself).@Nullable public T cast(@Nullable Object obj)
Class
object.obj
- the object to be castClassCastException
- if the object is not null and is not assignable to the type T.public boolean desiredAssertionStatus()
Few programmers will have any need for this method; it is provided for the benefit of the JRE itself. (It allows a class to determine at the time that it is initialized whether assertions should be enabled.) Note that this method is not guaranteed to return the actual assertion status that was (or will be) associated with the specified class when it was (or will be) initialized.
public static Class<?> forName(String className) throws ClassNotFoundException
Class
object associated with the class or interface with the given string
name.
For example, the following code fragment returns the runtime Class
descriptor for the
class named java.lang.Thread
:
Class t = Class.forName("java.lang.Thread")
A call to forName("X")
causes the class named X
to be initialized.
className
- the fully qualified name of the desired class.Class
object for the class with the specified name.LinkageError
- if the linkage failsExceptionInInitializerError
- if the initialization provoked by this method failsClassNotFoundException
- if the class cannot be locatedpublic String getName()
Class
object, as a String
.
If this class object represents a reference type that is not an array type then the binary name of the class is returned, as specified by The Java™ Language Specification.
If this class object represents a primitive type or void, then the name returned is a
String
equal to the Java language keyword corresponding to the primitive type or void.
If this class object represents a class of arrays, then the internal form of the name consists of
the name of the element type preceded by one or more '[
' characters representing the
depth of the array nesting. The encoding of element type names is as follows:
no_caption Element Type Encoding boolean Z byte B char C class or interface Lclassname; double D float F int I long J short S
The class or interface name classname is the binary name of the class specified above.
Examples:
String.class.getName() returns "java.lang.String" (new Object[3]).getClass().getName() returns "[Ljava.lang.Object;" (new int[3][4][5][6][7][8][9]).getClass().getName() returns "[[[[[[[I"
@Nullable public Package getPackage()
@Nullable public InputStream getResourceAsStream(String name)
Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:
name
begins with a '/'
('\u002f'
), then the absolute
name of the resource is the portion of the name
following the '/'
.
modified_package_name/name
Where the modified_package_name
is the package name of this object with '/'
substituted for '.'
( '\u002e'
).
name
- name of the desired resourceInputStream
object or null
if no resource with this name is
foundNullPointerException
- If name
is null
public String getSimpleName()
The simple name of an array is the simple name of the component type with "[]" appended. In particular the simple name of an array whose component type is anonymous is "[]".
@Nullable public Class<? super T> getSuperclass()
Class
representing the superclass of the entity (class, interface, primitive
type or void) represented by this Class
. If this Class
represents either the
Object
class, an interface, a primitive type, or void, then null is returned. If this
object represents an array class then the Class
object representing the Object
class is returned.public boolean isArray()
Class
object represents an array class.true
if this object represents an array class; false
otherwise.public boolean isAssignableFrom(Class<?> cls)
Class
object is either the same
as, or is a superclass or superinterface of, the class or interface represented by the specified
Class
parameter. It returns true
if so; otherwise it returns false
. If
this Class
object represents a primitive type, this method returns true
if the
specified Class
parameter is exactly this Class
object; otherwise it returns
false
.
Specifically, this method tests whether the type represented by the specified Class
parameter can be converted to the type represented by this Class
object via an identity
conversion or via a widening reference conversion. See The Java Language Specification,
sections 5.1.1 and 5.1.4 , for details.
cls
- the Class
object to be checkedboolean
value indicating whether objects of the type cls
can be
assigned to objects of this classNullPointerException
- if the specified Class parameter is null.public boolean isInstance(@Nullable Object obj)
Object
is assignment-compatible with the object represented
by this Class
. This method is the dynamic equivalent of the Java language
instanceof
operator. The method returns true
if the specified Object
argument is non-null and can be cast to the reference type represented by this Class
object without raising a ClassCastException.
It returns false
otherwise.
Specifically, if this Class
object represents a declared class, this method returns
true
if the specified Object
argument is an instance of the represented class (or
of any of its subclasses); it returns false
otherwise. If this Class
object
represents an array class, this method returns true
if the specified Object
argument can be converted to an object of the array class by an identity conversion or by a
widening reference conversion; it returns false
otherwise. If this Class
object
represents an interface, this method returns true
if the class or any superclass of the
specified Object
argument implements this interface; it returns false
otherwise.
If this Class
object represents a primitive type, this method returns false
.
obj
- the object to checkobj
is an instance of this classpublic boolean isInterface()
Class
object represents an interface type.true
if this object represents an interface; false
otherwise.public T newInstance() throws InstantiationException, IllegalAccessException
Class
object. The class is
instantiated as if by a new
expression with an empty argument list. The class is
initialized if it has not already been initialized.IllegalAccessException
- if the class or its nullary constructor is not accessible.InstantiationException
- if this Class
represents an abstract class, an interface, an array class, a
primitive type, or void; or if the class has no nullary constructor; or if the
instantiation fails for some other reason.ExceptionInInitializerError
- if the initialization provoked by this method fails.public String toString()
getName
. If this Class
object represents a primitive type, this method returns
the name of the primitive type. If this Class
object represents void this method returns
"void".