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
:
- Dynamic loading:
class.forName()
loads a class dynamically at runtime, whilenew
creates an instance of a class that is known at compile time. - Class loading:
class.forName()
loads the class using theClassLoader
mechanism, whilenew
uses the class loader that is associated with the current class loader. - Instance creation:
class.forName()
returns aClass
object, which can be used to create an instance of the class using thenewInstance()
method.new
creates an instance of the class directly. - Error handling: If the class cannot be loaded using
class.forName()
, aClassNotFoundException
is thrown. If the class cannot be instantiated usingnew
, aInstantiationException
orIllegalAccessException
may be thrown.
When to use each:
- Use
class.forName()
when you need to dynamically load a class at runtime, such as in a plugin architecture or when working with dynamic class loading. - Use
new
when you know the name of the class at compile time and want to create an instance of that class.