java.lang.Class class in JavaThe 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:
ExampleFilename: 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 objectCreating 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:
Return Type:
Overrides:
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:
Returns:
Exception: The method may throw the following exceptions:
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:
Returns:
Throws:
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:
Parameters:
Returns:
Throws:
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:
Return Type:
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:
Return Type:
Throws
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:
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:
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:
Return Type:
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:
Return Type:
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:
Return:
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:
Return:
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:
Return Type:
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:
Return Type:
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:
Return Type:
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:
Return Type:
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:
Return Type:
Throws:
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:
Return Type:
Throws:
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:
Return Type:
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:
Return Type:
Throws:
Filename: GenericTypeDemo.java Output: java.util.ArrayList Class<?>[] getInterfaces()The `java.lang.Class.getInterfaces()` method identifies the interfaces implemented by the class or interface that this object represents. Syntax: Return Type:
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:
Throws:
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:
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:
Return:
Throws:
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:
Throws:
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:
Throws:
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:
Throws:
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:
Return Type:
Throws:
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:
Returns:
Throws:
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:
Return:
Throws:
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:
Return:
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:
Return Type:
Throws:
Filename: ExampleClassExtends.java Output: Integer class cast as a subclass of Number: java.lang.Integer Next TopicReverse Level Order Traversal in Java |