May I know how does Class.forName("ClassName") different from ClassName.class. For example, I tried to execute the following
My output :
Also, I tried the following,
My output:
So doesn't it load the class when I say ClassName.class, but loads only when I use the Class Object to get constructors(cls.getConstructors()) or methods?
The main difference is in the required availability of the class. With ClassName.class the class needs to be available at compile time. If the class is missing while you are compiling you will get a compiler error. With Class.forName("ClassName") the class doesn't need to be there at compile time, only at runtime.
Another important difference is the generic type. ClassName.class returns a Class<ClassName>. Class.forName("ClassName") returns a Class<?> - the actual type is not known.
Class.forName actually loads the class. ClassName.class doesn't load the classbecause it's not necessary to do so. If you instantiate the class or access a static member (method, field) then the class is loaded, but not just by calling ClassName.class.
Guess I was wrong. It's loaded all right (as can be seen when running the JVM with -verbose), just not initialized. That only happens when instantiating or accessing a static member.