Home » Java programming language

Java Class class forName() method with example

Class class forName() method: Here, we are going to learn about the forName() method of Class class with its syntax and example.
Submitted by Preeti Jain, on November 21, 2019

Class class forName() method

  • forName() method is available in java.lang package.
  • forName() method is used to return the class object for the Class with the given class_name.
  • forName() method is a static method, it is accessible with the class name and if we try to access the method with the class object then we will not get any error.
  • forName() method may throw an exception at the time of returning a Class object.
    • LinkageError: This exception may throw when we get linking error.
    • ExceptionInInitializeError: In this exception when the initialization is done by this method fails.
    • ClassNotFoundException: In this exception when the given class does not exist.

Syntax:

    public static Class forName(String class_name);

Parameter(s):

  • String class_name – represents the fully qualified name of the given class.

Return value:

The return type of this method is Class, it returns this Class object for the class with the given name.

Example:

// Java program to demonstrate the example 
// of Class forName (String class_name) method of Class 

public class ForNameOfClass {
    public static void main(String[] args) throws Exception {
        // It returns the Class 'java.lang.Object' object for the class     
        // with the given class name
        Class cl = Class.forName("java.lang.Object");

        // Display Name, Package and Interfaces
        System.out.print("Class 'java.lang.Object' Name: ");
        System.out.println(cl.getName());

        System.out.print("Class 'java.lang.Object' Package: ");
        System.out.println(cl.getPackage());

        System.out.print("Class 'java.lang.Object' Interface: ");
        System.out.println(cl.getInterfaces());
    }
}

Output

Class 'java.lang.Object' Name: java.lang.Object
Class 'java.lang.Object' Package: package java.lang
Class 'java.lang.Object' Interface: [Ljava.lang.Class;@68f7aae2



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.