Class Class<T>
- java.lang.Object
-
- java.lang.Class<T>
-
- Type Parameters:
T- the type of the class modeled by thisClassobject. For example, the type ofString.classisClass<String>. UseClass<?>if the class being modeled is unknown.
- All Implemented Interfaces:
Serializable,AnnotatedElement,GenericDeclaration,Type
public final class Class<T> extends Object implements AnnotatedElement, GenericDeclaration, Serializable, Type
Instances of the classClassrepresent 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 aClassobject 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, anddouble), and the keywordvoidare also represented asClassobjects.Classhas no public constructor. InsteadClassobjects are constructed automatically by the Java Virtual Machine as classes are loaded.The following example uses a
Classobject 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
Classobject 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());- See Also:
- Serialized Form
-
-
Constructor Summary
Constructors Constructor Description Class()
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description <U> Class<? extends U>asSubclass(Class<U> clazz)Casts thisClassobject to represent a subclass of the class represented by the specified class object.Tcast(Object obj)Casts an object to the class or interface represented by thisClassobject.booleandesiredAssertionStatus()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 theClassobject associated with the class or interface with the given string name.StringgetName()Returns the name of the entity (class, interface, array class, primitive type, or void) represented by thisClassobject, as aString.PackagegetPackage()Gets the package for this class.InputStreamgetResourceAsStream(String name)Finds a resource with a given name.StringgetSimpleName()Returns the simple name of the underlying class as given in the source code.Class<? super T>getSuperclass()Returns theClassrepresenting the superclass of the entity (class, interface, primitive type or void) represented by thisClass.booleanisArray()Determines if thisClassobject represents an array class.booleanisAssignableFrom(Class<?> cls)Determines if the class or interface represented by thisClassobject is either the same as, or is a superclass or superinterface of, the class or interface represented by the specifiedClassparameter.booleanisInstance(Object obj)Determines if the specifiedObjectis assignment-compatible with the object represented by thisClass.booleanisInterface()Determines if the specifiedClassobject represents an interface type.TnewInstance()Creates a new instance of the class represented by thisClassobject.StringtoString()Converts the object to a string.
-
-
-
Method Detail
-
forName
public static Class<?> forName(String className) throws ClassNotFoundException
Returns theClassobject associated with the class or interface with the given string name.For example, the following code fragment returns the runtime
Classdescriptor for the class namedjava.lang.Thread:Class t = Class.forName("java.lang.Thread")A call to
forName("X")causes the class namedXto be initialized.- Parameters:
className- the fully qualified name of the desired class.- Returns:
- the
Classobject for the class with the specified name. - Throws:
LinkageError- if the linkage failsExceptionInInitializerError- if the initialization provoked by this method failsClassNotFoundException- if the class cannot be located
-
asSubclass
public <U> Class<? extends U> asSubclass(Class<U> clazz)
Casts thisClassobject to represent a subclass of the class represented by the specified class object. Checks that the cast is valid, and throws aClassCastExceptionif 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
Classobject to pass it to an API that restricts theClassobjects 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).- Type Parameters:
U- the type to cast this class object to- Parameters:
clazz- the class of the type to cast this class object to.- Returns:
- this
Classobject, cast to represent a subclass of the specified class object. - Throws:
ClassCastException- if thisClassobject does not represent a subclass of the specified class (here "subclass" includes the class itself).
-
cast
@Nullable public T cast(@Nullable Object obj)
Casts an object to the class or interface represented by thisClassobject.- Parameters:
obj- the object to be cast- Returns:
- the object after casting, or null if obj is null
- Throws:
ClassCastException- if the object is not null and is not assignable to the type T.
-
desiredAssertionStatus
public 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. If this class has had its assertion status set, the most recent setting will be returned; otherwise, if any package default assertion status pertains to this class, the most recent setting for the most specific pertinent package default assertion status is returned; otherwise, the system class default assertion status is returned.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.
- Returns:
- the desired assertion status of the specified class.
-
getName
public String getName()
Returns the name of the entity (class, interface, array class, primitive type, or void) represented by thisClassobject, as aString.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
Stringequal 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"- Returns:
- the name of the class or interface represented by this object.
-
getPackage
@Nullable public Package getPackage()
Gets the package for this class. Null is returned if no package object was created by the class loader of this class.- Returns:
- the package of the class, or null if no package information is available from the archive or codebase.
-
getResourceAsStream
@Nullable public InputStream getResourceAsStream(String name)
Finds a resource with a given name.Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:
- If the
namebegins with a'/'('\u002f'), then the absolute name of the resource is the portion of thenamefollowing the'/'. - Otherwise, the absolute name is of the following form:
modified_package_name/nameWhere the
modified_package_nameis the package name of this object with'/'substituted for'.'('\u002e').
- Parameters:
name- name of the desired resource- Returns:
- A
InputStreamobject ornullif no resource with this name is found - Throws:
NullPointerException- Ifnameisnull
- If the
-
getSimpleName
public String getSimpleName()
Returns the simple name of the underlying class as given in the source code. Returns an empty string if the underlying class is anonymous.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 "[]".
- Returns:
- the simple name of the underlying class
-
getSuperclass
@Nullable public Class<? super T> getSuperclass()
Returns theClassrepresenting the superclass of the entity (class, interface, primitive type or void) represented by thisClass. If thisClassrepresents either theObjectclass, an interface, a primitive type, or void, then null is returned. If this object represents an array class then theClassobject representing theObjectclass is returned.- Returns:
- the superclass of the class represented by this object.
-
isArray
public boolean isArray()
Determines if thisClassobject represents an array class.- Returns:
trueif this object represents an array class;falseotherwise.
-
isAssignableFrom
public boolean isAssignableFrom(Class<?> cls)
Determines if the class or interface represented by thisClassobject is either the same as, or is a superclass or superinterface of, the class or interface represented by the specifiedClassparameter. It returnstrueif so; otherwise it returnsfalse. If thisClassobject represents a primitive type, this method returnstrueif the specifiedClassparameter is exactly thisClassobject; otherwise it returnsfalse.Specifically, this method tests whether the type represented by the specified
Classparameter can be converted to the type represented by thisClassobject 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.- Parameters:
cls- theClassobject to be checked- Returns:
- the
booleanvalue indicating whether objects of the typeclscan be assigned to objects of this class - Throws:
NullPointerException- if the specified Class parameter is null.
-
isInstance
public boolean isInstance(@Nullable Object obj)
Determines if the specifiedObjectis assignment-compatible with the object represented by thisClass. This method is the dynamic equivalent of the Java languageinstanceofoperator. The method returnstrueif the specifiedObjectargument is non-null and can be cast to the reference type represented by thisClassobject without raising aClassCastException.It returnsfalseotherwise.Specifically, if this
Classobject represents a declared class, this method returnstrueif the specifiedObjectargument is an instance of the represented class (or of any of its subclasses); it returnsfalseotherwise. If thisClassobject represents an array class, this method returnstrueif the specifiedObjectargument can be converted to an object of the array class by an identity conversion or by a widening reference conversion; it returnsfalseotherwise. If thisClassobject represents an interface, this method returnstrueif the class or any superclass of the specifiedObjectargument implements this interface; it returnsfalseotherwise. If thisClassobject represents a primitive type, this method returnsfalse.- Parameters:
obj- the object to check- Returns:
- true if
objis an instance of this class
-
isInterface
public boolean isInterface()
Determines if the specifiedClassobject represents an interface type.- Returns:
trueif this object represents an interface;falseotherwise.
-
newInstance
public T newInstance() throws InstantiationException, IllegalAccessException
Creates a new instance of the class represented by thisClassobject. The class is instantiated as if by anewexpression with an empty argument list. The class is initialized if it has not already been initialized.- Returns:
- a newly allocated instance of the class represented by this object.
- Throws:
IllegalAccessException- if the class or its nullary constructor is not accessible.InstantiationException- if thisClassrepresents 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.
-
toString
public String toString()
Converts the object to a string. The string representation is the string "class" or "interface", followed by a space, and then by the fully qualified name of the class in the format returned bygetName. If thisClassobject represents a primitive type, this method returns the name of the primitive type. If thisClassobject represents void this method returns "void".
-
-