Package java.lang

Class Class<T>

  • Type Parameters:
    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.
    All Implemented Interfaces:
    Serializable, AnnotatedElement, GenericDeclaration, Type

    public final class Class<T>
    extends Object
    implements AnnotatedElement, GenericDeclaration, Serializable, Type
    Instances of the class 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());
    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 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.
    • Constructor Detail

      • Class

        public Class()
    • Method Detail

      • forName

        public static Class<?> forName​(String className)
                                throws ClassNotFoundException
        Returns the 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.

        Parameters:
        className - the fully qualified name of the desired class.
        Returns:
        the Class object for the class with the specified name.
        Throws:
        LinkageError - if the linkage fails
        ExceptionInInitializerError - if the initialization provoked by this method fails
        ClassNotFoundException - if the class cannot be located
      • asSubclass

        public <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. 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).

        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 Class object, cast to represent a subclass of the specified class object.
        Throws:
        ClassCastException - if this Class object 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 this Class object.
        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 this 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"
         
        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 name begins with a '/' ('\u002f' ), then the absolute name of the resource is the portion of the name following the '/'.
        • Otherwise, the absolute name is of the following form:
          modified_package_name/name

          Where the modified_package_name is the package name of this object with '/' substituted for '.' ( '\u002e').

        Parameters:
        name - name of the desired resource
        Returns:
        A InputStream object or null if no resource with this name is found
        Throws:
        NullPointerException - If name is null
      • 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 the 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.
        Returns:
        the superclass of the class represented by this object.
      • isArray

        public boolean isArray()
        Determines if this Class object represents an array class.
        Returns:
        true if this object represents an array class; false otherwise.
      • isAssignableFrom

        public 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. 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.

        Parameters:
        cls - the Class object to be checked
        Returns:
        the boolean value indicating whether objects of the type cls can 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 specified 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.

        Parameters:
        obj - the object to check
        Returns:
        true if obj is an instance of this class
      • isInterface

        public boolean isInterface()
        Determines if the specified Class object represents an interface type.
        Returns:
        true if this object represents an interface; false otherwise.
      • newInstance

        public T newInstance()
                      throws InstantiationException,
                             IllegalAccessException
        Creates a new instance of the class represented by this 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.
        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 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.
      • 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 by 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".
        Overrides:
        toString in class Object
        Returns:
        a string representation of this class object.