java.lang.Class class in Java

The java.lang.Class class serves as a fundamental element of Java's Reflective Application Programming Interface (API), enabling software engineers to examine and modify classes through their coding process. As part of the java.lang package, it specifically refers to a particular class within a Java application. Objects instantiated from the Class class represent classes and interfaces in a Java program which is presently running. The Java "Class" class provides basic data types like Boolean, Byte, Char, Short, Int, Long, and FloatingPoint values. In contrast to most other classes, "Class" does not have a public constructor, instead, it is created at runtime by the Java Virtual Machine (JVM) during execution.

The Class class in Java functions as a representation of both classes and interfaces present in a currently running Java program. It offers various methods for retrieving details about a class, including its name, superclass, implemented interfaces, and methods.

Methods of the Class class:

MethodDescription
getName()The `getName()` method, belonging to the `java.lang.Class` class, returns the fully qualified name of the class or interface represented by the Class object. It is frequently utilized in Reflection for acquiring the full class name, which includes the package name when applicable.
getSimpleName()The getSimpleName() method is part of the java.lang.Class class retrieves the simple name of the class or interface represented by the Class object in the Reflection API.
getSuperclass()It returns the Class object representing the superclass of the class or interface represented by this Class object.
getInterfaces()It returns an array of Class objects representing the interfaces implemented by the class or interface represented by the current Class object.
getField(String name)It is used to obtain a Field object representing a specific public field with the given name in the class or interface represented by the current Class object.
getMethod(String name, Class<?>… parameterTypes)It is used to obtain a Method object that represents a specific public method with the given name and parameter types in the class or interface represented by the current Class object.
newInstance()It creates a new instance of the class it represents, assuming it has a public, no-argument constructor.
isInstance(Object obj)The isInstance(Object obj) method is part of the java.lang.Class class in the Reflection API checks whether the provided object is an instance of the class or interface represented by the current Class object, returning true or false accordingly.
isAssignableFrom(Class<?> cls)It checks if the class or interface represented by the current Class object is assignable from the specified class or interface (cls), returning true or false accordingly.

Example

Filename: ClassInfoExample.java

Output:

The class name is: java.lang.String
The simple class name is: String
The superclass is: java.lang.Object
The interfaces implemented are: [interface java.io.Serializable, interface java.lang.Comparable, interface java.lang.CharSequence]
Is it possible to assign String to Object? false

Creating a Class object

Creating a Class object in Java can be accomplished through various methods. Here are three commonly used approaches:

1. Class.forName("className"):

The Class.forName(String className) method is a static factory method for the Class class. It creates a Class object for the specified class name provided as a string. The name of the class must include the complete path, known as the fully qualified name, for the specific class we want.

Syntax:

2. MyClass.class:

Appending .class after a class name references the Class object representing that class. The approach is used when the class name is known at compile-time. It is often used with primitive data types.

Syntax:

3. obj.getClass():

The `getClass()` method belongs to the Object class. It gives the actual class of the object when we use it. It is useful when we want to figure out the class type while the program is running.

Syntax:

Methods:

String toString():

The method turns a Class object into a string by adding either "class" or "interface," then a space, and finally, the complete name of the class to which the object belongs. If the Class object shows a basic data type, the method gives back the name of that type; otherwise, it returns "void."

Syntax:

Parameters:

  • None

Return Type:

  • Returns a string representation of the current class object.

Overrides:

  • The method overrides the toString method in the Object class.

Filename: StringDemo.java

Output:

Output String 1: Hello World
Output String 2: Welcome to javatpoint

Class<?> forName(String className)

It returns the Class object associated with the class or interface with the given string name.

Syntax:

Parameters:

  • className: A String representing the fully qualified name of the class or interface to be loaded.

Returns:

  • Return the Class object associated with the class that has the provided name.

Exception: The method may throw the following exceptions:

  • LinkageError: The exception is thrown if there is a failure in linking the class.
  • ExceptionInInitializerError: If the initialization triggered by this method encounters an error, this exception is thrown.
  • ClassNotFoundException: The exception is thrown if the specified class cannot be found.

Filename: ClassLoadingExample.java

Output:

Loaded Class Name: java.util.ArrayList

Class<?> forName(String className,boolean initialize, ClassLoader loader):

The method also provides the Class object linked to the class or interface identified by the given string name, utilizing the supplied class loader. The specified class loader is responsible for loading the class or interface. In the absence of a specified `loader` parameter or if it is null, the class will be loaded through the Bootstraps Class Loader during its initialization process, which occurs only when the `initialize` parameter is set to `true` and the class has not previously undergone initialization.

Syntax:

Parameters:

  • className: A String representing the fully qualified name of the class to be loaded.
  • initialize: A boolean indicating whether the class should be initialized. If true, the class will be initialized; if false, it will not be initialized.
  • loader: A ClassLoader object used to load the class. If null, the default system class loader will be used.

Returns:

  • Retrieve the Class object representing the class with the provided name.

Throws:

  • LinkageError: Occurs if there is a failure in linking the class.
  • ExceptionInInitializerError: Arises if the initialization triggered by this method encounters an error.
  • ClassNotFoundException: Thrown if the specified class cannot be found.

Filename: DynamicClassLoadingDemo.java

Output:

Class represented by loadedClass: class java.lang.String

T newInstance():

The `newInstance()` method creates a new instance of the class represented by the calling object. It is a way to dynamically instantiate an object without explicitly using the `new` keyword. The type of the new instance is based on the type of the object calling the method. Keep in mind that this method assumes the class has a default (parameterless) constructor, and it might throw exceptions if this condition is not met or if there are other instantiation issues.

Syntax:

Type Parameter:

  • T: Represents the class type for which an instance will be created.

Parameters:

  • No parameters are required.

Returns:

  • The object represents a newly allocated instance of the class.

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.
  • SecurityException: If a security manager, s, is present.

boolean isInstance(Object obj)

The method checks if the given object can be assigned to the type represented by this Class. It is similarly to the instanceof operator in Java, verifying whether the specified object is compatible with the class it represents.

Syntax:

Parameters:

  • obj: The object to be checked for assignment compatibility with the class represented by the Class object.

Return Type:

  • boolean: It returns true if the specified object is an instance of the class or interface represented by the Class object, and false otherwise.

Filename: BooleanExample.java

Output:

Is sampleString an instance of String? : true
Is sampleDouble an instance of String? : false

boolean isAssignableFrom(Class<?> cls)

The method boolean isAssignableFrom, checks if one class can be used in place of another. It returns true if the class represented by the current object is the same as, or is a superclass or superinterface of, the specified class (`cls`). Otherwise, it returns false.

Syntax:

Parameters:

  • cls: The class to check against.

Return Type:

  • boolean: It returns true if the class represented by the current Class object is assignable from the specified class (cls). Otherwise, it returns false.

Throws

  • NullPointerException: If the provided Class parameter is null, the method will throw a NullPointerException.

Filename: ExampleBoolean.java

Output:

Is ExampleBoolean assignable from Thread class? : true
Is ExampleBoolean assignable from String class? : false

boolean isInterface()

The boolean isInterface() method determines whether the class or interface represented by the Class object is an interface.

Syntax:

Return Type:

  • boolean: It returns true if the class or interface represented by the Class object is an interface. Otherwise, it returns false.

Filename: booleanisInterface.java

Output:

Is String an interface? : false
Is Runnable an interface? : true

boolean isPrimitive()

The boolean isPrimitive() method determines whether the class represented by the Class object is a primitive data type.

Syntax:

Return Type:

  • boolean: It returns true if the class represented by the Class object is a primitive data type. Otherwise, it returns false.

Filename: booleanisPrimitive.java

Output:

Is int a primitive type? : true
Is String a primitive type? : false

boolean isArray()

It is used to determine whether the Class object represents an array class or not. The method returns true if the class is an array class and false otherwise.

Syntax:

Parameters:

  • The method takes no parameters.

Return Type:

  • boolean: It returns true if the class represents an array class; otherwise, it returns false.

Filename: ArrayCheckExample.java

Output:

The class represented by [I is an array: true
The class represented by ArrayCheckExample is an array: false

boolean isAnonymousClass()

The method yields a true result only if the current class is an anonymous class. An anonymous class is similar to a local class, with the key distinction that it does not possess a specified name.

Syntax:

Parameters:

  • The method does not take any parameters.

Return Type:

  • The return type is boolean, indicating that the method returns a true/false value. It returns true if the current class is anonymous and false otherwise.

Filename: AnonymousExample.java

Output:

Class Name = AnonymousExample
Is this an Anonymous Class? false

boolean isLocalClass()

The isLocalClass() method determines whether a class is declared within a method, making it a local class. It returns true if the class is local and false otherwise.

Syntax:

Parameters:

  • The method does not take any parameters.

Return:

  • The return type is boolean, indicating that the method returns a true/false value. It returns true if the class is a local class and false otherwise.

Filename: LocalClassExample.java

Output:

Class Name = LocalClassExample
Is this a LocalClass? false

boolean isMemberClass()

The isMemberClass() method is part of the Class class in Java and is used to determine whether the class represents a member (non-local and non-anonymous) class. A member class is a class that is directly defined within another class or interface.

Syntax:

Parameters:

  • The method takes no parameters.

Return:

  • The return type is boolean, indicating that the method returns a true/false value. It returns true if the class represents a member (non-local and non-anonymous) class and false otherwise.

Filename: MemberClassExample.java

Output:

The class name is: MemberClassExample
Is this class a member class? false

boolean isEnum()

It is used to determine whether the Class object represents an enumeration type or not.

Syntax:

Parameters:

  • The above method takes no parameters.

Return Type:

  • boolean: It returns true if the class represents an enumeration type; otherwise, it returns false.

Filename: EnumCheckExample.java

Output:

TrafficLight is an Enum class: true
EnumCheckExample is an Enum class: false

boolean isAnnotation()

It is used to determine whether the Class object represents an annotation type or not. The method returns true if the class is an annotation type and false otherwise.

Syntax:

Parameters:

  • The above method takes no parameters.

Return Type:

  • boolean: It returns true if the class represents an annotation type; otherwise, it returns false.

Filename: AnnotationCheckExample.java

Output:

MyAnnotation is an annotation type: true
AnnotationCheckExample is an annotation type: false

String getName()

It is used to obtain the fully qualified name of the class, interface, array, or primitive type represented by the Class object. The method returns a String that contains the name.

Syntax:

Parameters:

  • The method takes no parameters.

Return Type:

  • String: It returns the fully qualified name of the class or type represented by the Class object.

Filename: GetNameExample.java

Output:

Name of class String: java.lang.String

String getSimpleName()

The getSimpleName() method, belonging to the java.lang.Class class in Java retrieves the name of the underlying class as specified in the source code. If the underlying class is anonymous, the method returns an empty string. In the case of an array, the simple name is derived from the component type, followed by "[]" to indicate an array. Specifically, the simple name is represented as "[]" for an array with an anonymous component type.

Syntax:

Parameters:

  • The method takes no parameters.

Return Type:

  • String: It returns the simple name of the class or interface represented by the Class object.

Filename: GetSimpleNameExample.java

Output:

Simple name of class String: String
Simple name of class Integer: Integer

ClassLoader getClassLoader()

It is used to obtain the class loader for the class or interface represented by the Class object. The method returns the ClassLoader object that loaded the class or interface.

Syntax:

Parameters:

  • The method takes no parameters.

Return Type:

  • ClassLoader: It returns the class loader for the class or interface represented by the Class object.

Throws:

  • SecurityException: The getClassLoader() method can throw a SecurityException if a security manager restricts access to the class loader for the respective class.

Filename: GetClassLoaderExample.java

Output:

Class loader for String class: null
Class loader for current class: jdk.internal.loader.ClassLoaders$AppClassLoader@5cb0d902

TypeVariable<Class<T>>[ ] getTypeParameters()

It is used to obtain an array of TypeVariable objects representing the type parameters declared by the generic class or interface represented by the Class object.

Syntax:

Parameters:

  • The method takes no parameters.

Return Type:

  • TypeVariable<Class<T>>[]: It returns an array of TypeVariable objects representing the type parameters of the generic class or interface.

Throws:

  • GenericSignatureFormatError: if the generic signature of the class or interface does not follow the prescribed format specified by the Java Virtual Machine (JVM).

Filename: TypeVariableDemo.java

Output:

Type parameter of List class: E

Class<? super T> getSuperclass()

It is used to obtain the Class object representing the superclass of the class or interface represented by the Class object. If the class represented by this Class object is an interface, the method returns null.

Syntax:

Parameters:

  • The method takes no parameters.

Return Type:

  • Class<? super T>: It returns the Class object representing the superclass of the class or interface represented by the Class object.

Filename: GetSuperclassExample.java

Output:

Instance 1 is an object of type: SuperClass
Superclass of Instance 1: java.lang.Object
Instance 2 is an object of type: SubClass
Superclass of Instance 2: SuperClass

Type getGenericSuperclass()

The Type getGenericSuperclass() method retrieves the Type that represents the immediate superclass of the entity, which can be a class, interface, primitive type, or void, as encapsulated by this Class instance.

Syntax:

Parameters:

  • The method takes no parameters.

Return Type:

  • Type: It returns the Type object representing the generic superclass of the class or interface.

Throws:

  • GenericSignatureFormatError: The generic class signature deviates from the prescribed format outlined in the Java Virtual Machine Specification, 3rd edition
  • TypeNotPresentException: If the generic superclass refers to a type declaration that doesn't exist, a TypeNotPresentException may be thrown.
  • MalformedParameterizedTypeException: If the generic superclass refers to a parameterized type that cannot be instantiated for any reason.

Filename: GenericTypeDemo.java

Output:

java.util.ArrayList
class java.lang.Integer

Class<?>[] getInterfaces()

The `java.lang.Class.getInterfaces()` method identifies the interfaces implemented by the class or interface that this object represents.

Syntax:

Return Type:

  • Class<?>[]: It returns an array of Class objects representing the interfaces implemented by the class or interface.

Filename: GetInterfacesExample.java

Output:

Interfaces implemented by java.lang.String:
java.io.Serializable
java.lang.Comparable
java.lang.CharSequence

Type[] getGenericInterfaces()

It is used to obtain the array of Type objects that represent the generic interfaces implemented by the class or interface represented by the current Class object.

Syntax:

Return Type:

  • Type[]: It returns an array of Type objects representing the generic interfaces implemented by the class or interface.

Throws:

  • GenericSignatureFormatError occurs when the generic class signature doesn't adhere to the specified format in the Java Virtual Machine Specification, 3rd edition.
  • TypeNotPresentException: Thrown if any generic superinterfaces refer to a type declaration that doesn't exist.
  • MalformedParameterizedTypeException: Raised when any of the generic superinterfaces refer to a parameterized type that cannot be instantiated.

Filename: GetGenericInterfacesExample.java

Output:

Interfaces implemented by Set interface:
java.util.Collection

Package getPackage()

It is used to retrieve the package for the class or interface represented by the current Class object.

Syntax:

Return Type:

  • Package: It returns the Package object representing the package of the class or interface.

Filename: GetPackageExample.java

Output:

Package of java.lang.String: java.lang

Field[] getFields()

The `getFields()` method in Java is a part of the `Field` class and is used to retrieve an array of `Field` objects that represent the fields of a particular class or interface.

Syntax:

Parameters:

  • The method does not contain any parameters

Return:

  • The return type of getFields() is Field[]. It returns an array of Field objects representing the public fields of the class or interface.

Throws:

  • SecurityException: If a security manager, s, is present.

Filename: GetFieldsExample.java

Output:

Below are the fields of Integer class:
public static final int java.lang.Integer.MIN_VALUE
public static final int java.lang.Integer.MAX_VALUE
public static final java.lang.Class java.lang.Integer.TYPE
public static final int java.lang.Integer.SIZE
public static final int java.lang.Integer.BYTES

Class<?>[ ] getClasses()

It is used to get an array of Class objects representing the public member classes and interfaces of the current Class object class.

Syntax:

Return:

  • The method returns an array of Class<?> objects, representing the public member classes and interfaces of the class.

Throws:

  • SecurityException: If a security manager, s, is present.

Filename: GetClassesExample.java

Output:

Public Member Classes of GetClassesExample:

Method[] getMethods()

It is used to retrieve an array of Method objects reflecting the public methods of the class or interface represented by the current Class object. It includes public methods from the class itself and its superclasses and interfaces.

Syntax:

Return:

  • The method returns an array of Method objects representing the public methods of the class or interface.

Throws:

  • SecurityException: If a security manager, s, is present.

Filename: GetMethodsExample.java

Output:

Public Methods of MyClass:
method1
method2
wait
wait
wait
equals
toString
hashCode
getClass
notify
notifyAll

Constructor<?>[] getConstructors()

It is used to retrieve an array of Constructor objects reflecting all the public constructors of the class or interface represented by the current Class object.

Syntax:

Return:

  • The method returns an array of Constructor<?> objects, representing the public constructors of the class or interface.

Throws:

  • SecurityException: If a security manager, s, is present.

Filename: ConstructorsExample.java

Output:

Constructors of Boolean class:public java.lang.Boolean(boolean)
public java.lang.Boolean(java.lang.String)

Field getField(String fieldName)

It is used to get a Field object that reflects the specified public member field of the class or interface represented by the current Class object.

Syntax:

Parameters:

  • fieldName: The name of the field.

Return Type:

  • The method returns a Field object representing the specified public field.

Throws:

  • NoSuchFieldException: Occurs if the specified field name is not found or accessible.
  • NullPointerException: Arises when the provided field name is null.
  • SecurityException: It may be thrown if a security manager is present and certain security conditions related to package access and definition are not met.

Filename: ExampleGetField.java

Output:

Public field in Integer class with MIN_VALUE name:
public static final int java.lang.Integer.MIN_VALUE

Method getMethod(String methodName,Class… parameterTypes)

The method retrieves a `Method` object, providing comprehensive reflection details about a specific public method associated with the class or interface represented by the current Class object.

Syntax:

Parameters:

  • methodName: A string representing the name of the method we want to retrieve.
  • parameterTypes: A variable number of Class objects representing the method's parameter types.

Returns:

  • The method returns the method object of the class specified by the given name.

Throws:

  • NoSuchMethodException: Thrown if a method with the specified name is not found.
  • NullPointerException: Thrown if the provided method name is null.
  • SecurityException: Thrown if a security manager (s) is present.

Filename: ExampleMethodGetMethod.java

Output:

Details of the 'length' method in the String class:
Method Name: length
Return Type: int

Constructor<?> getConstructor(Class<?>… parameterTypes)

The method fetches a Constructor object that represents a particular public constructor of the class indicated by the current Class object. The parameterTypes parameter is an array of Class objects, specifying the types of parameters for the constructor, arranged in the order they are declared.

Syntax:

Parameters:

  • parameterTypes: An array of Class objects representing the formal parameter types of the constructor, in declared order.

Return:

  • Returns a Constructor object reflecting the specified public constructor of the class represented by this Class object.

Throws:

  • NoSuchMethodException: If a constructor with the specified parameter types is not found.
  • SecurityException: If a security manager is present.

Filename: ExampleConstructor.java

Output:

Constructor in Integer class with String parameter:
public java.lang.Integer(java.lang.String) throws java.lang.NumberFormatException

T cast(Object obj)

The method converts an object to the class or interface this `Class` object indicates.

Syntax:

Parameters:

  • obj: The object to be cast.

Return:

  • Returns the object after casting it to the generic type T. The result type (T) is inferred based on the context in which the method is called.

Filename: ExampleTCast.java

Output:

Casting Result: Hello, World!

<U> Class<? extends U> asSubclass(Class<U> clazz)

The method casts this Class object to represent a subclass of the class represented by the specified class object.

Syntax:

Parameters:

  • <U>: A generic type representing the target type.
  • clazz: A Class object indicating the target class or interface.

Return Type:

  • Class<? extends U>: The method returns a Class object representing the specified class or a subclass, ensuring it is a subclass of the target type U.

Throws:

  • ClassCastException: If the current Class object doesn't genuinely represent a subclass (including the class itself).

Filename: ExampleClassExtends.java

Output:

Integer class cast as a subclass of Number: java.lang.Integer





Latest Courses