Class forname vs new in java

In Java, class.forName() and new are two different ways to create an instance of a class, but they serve different purposes.

class.forName()

class.forName() is a method that loads a class by name and returns a Class object representing the class. It is used to dynamically load a class at runtime, without knowing its name at compile time.

Here's an example:

String className = "mypackage.MyClass";
Class<?> clazz = Class.forName(className);

In this example, Class.forName() loads the class mypackage.MyClass and returns a Class object representing that class. You can then use this Class object to create an instance of the class using the newInstance() method:

Object obj = clazz.newInstance();

new

new is a keyword in Java that is used to create a new instance of a class. It is used to create an instance of a class that is known at compile time.

Here's an example:

MyClass obj = new MyClass();

In this example, new creates a new instance of the MyClass class and assigns it to the obj variable.

Key differences

Here are the key differences between class.forName() and new:

  1. Dynamic loading: class.forName() loads a class dynamically at runtime, while new creates an instance of a class that is known at compile time.
  2. Class loading: class.forName() loads the class using the ClassLoader mechanism, while new uses the class loader that is associated with the current class loader.
  3. Instance creation: class.forName() returns a Class object, which can be used to create an instance of the class using the newInstance() method. new creates an instance of the class directly.
  4. Error handling: If the class cannot be loaded using class.forName(), a ClassNotFoundException is thrown. If the class cannot be instantiated using new, a InstantiationException or IllegalAccessException may be thrown.

When to use each: