What is Class.forName and how its working

 


In this tutorial we will see about what is Class.forName and few questions which each Java Programmer needs to know in it. 

  • What is Class.forName?
  • In which package "Class" present?
  • What is the return type of Class.forName and how its working?
  • What are all Exceptions/ Error thrown by Class.forName method?

What is Class.forName?



"Class" is a Java class with various methods defined in JDK. forName is a static method in "Class" class with 2 different parameterized (Method Overloading) as given below.

public static Class<?> forName(String className)
public static Class<?> forName(String name, boolean initialize, ClassLoader loader)

Class.forName is used to create the instance or object dynamically at run-time. 


In which package "Class" present?

"Class" class present in java.lang package. 


What is the return type of Class.forName and how its working?

Returns the Class instance associated with the class or interface with the given class name String. 
For example, if we need to create the instance dynamically for com.javadiscover.MyClass then following code will return the runtime Class descriptor 

MyClass obj = (MyClass) Class.forName("com.javadiscover.MyClass")


What are all Exceptions/ Error thrown by Class.forName method?

There are 3 types of Exception and Error will be thrown by forName method. They are

LinkageError - if the linkage fails
ExceptionInInitializerError - if the initialization provoked by this method fails
ClassNotFoundException - if the class cannot be located




2 comments:
Write comments