I will start with my example:
I have a class classload.Loadable
.
package classload;
public class Loadable {
static{
System.out.println("Loaded already.....");
}
public Loadable(){
System.out.println("Now created.....");
}
}
which will be loaded and created instance in the following 2 ways.
First:
public static void main(String[] args) throws Exception {
System.out.println("Starting .....");
Class.forName("classload.Loadable").newInstance();
}
Second:
public static void main(String[] args) throws Exception {
System.out.println("Starting .....");
classload.Loadable.class.newInstance();
}
Both gives same output as expected(since Class.forname
returns the same class
object):
Starting .....
Loaded already.....
Now created.....
I want to know which all scenarios we use Class.forname
and whereever we may use .class
object directly
The simplest solution is to use
new Loadable();
if the class is know at compile time and you expect it to be available at runtime. Note: this will throw a NoClassDefError
at runtime if it is not available.
If you are not sure it will be available a runtime, you might use
Class.forName("classload.Loadable").newInstance();
as it is clearer as to which exceptions will be thrown.
The problem with
classload.Loadable.class.newInstance()
is that it's not particularly useful in either context.
Note: Class.newInstance()
has a known issue were it will throw checked exceptions which you don't know about. i.e. if the Constructor throws a checked exception it won't be wrapped and the compiler can't tell what will be thrown.
Class.forName().newInstance()
loads class at runtime. It may succeed, or it may fail, depending on whether the desired class is valid or not. Means your instance created at runtime.
name.class.newInstance()
: class
is an class literal which evaluate as compile time constant. It can still fail at runtime if the referenced class is not valid and present within the classpath, but it can be used in places where constant expressions are required.
second calling type is equivalent to Loadable loadable = new Loadable()