Java forName() method

Java forName() method

The forName() method is a static method of the Class class in Java that is used to load a class at runtime.

Here's an example of how to use the forName() method to load a class at runtime:

public class Main {
  public static void main(String[] args) throws ClassNotFoundException {
    // Load the MyClass class at runtime
    Class<?> clazz = Class.forName("com.example.MyClass");

    // Print the name of the loaded class
    System.out.println(clazz.getName()); // prints "com.example.MyClass"
  }
}
‮‬Source:www.lautturi.com

This code uses the forName() method to load the MyClass class at runtime. The forName() method takes a fully qualified class name as an argument and returns a Class object representing the loaded class.

The Class object returned by the forName() method can be used to perform various operations on the class, such as getting its name, creating new instances of the class, or accessing its methods and fields.

Note that the forName() method may throw a ClassNotFoundException if the class cannot be found. This exception should be caught or declared to be thrown in the method where the forName() method is called.

You can find more information about the forName() method and the Class class in the Java documentation.

Created Time:2017-11-03 22:21:03  Author:lautturi