We can get class Class object by 3 methods:
- MyClass.class
- obj.getClass
- Class.forName("className")
I don't understood the difference between: MyClass.class
and Class.forName("className")
.
Because both will need Class Name.
We can get class Class object by 3 methods:
I don't understood the difference between: MyClass.class
and Class.forName("className")
.
Because both will need Class Name.
It dynamically load the class based on fully qualified class name string.
Returns the java.lang.Class object that represents the runtime class of the object.
A
class
literal is an expression consisting of the name of a class, interface, array, or primitive type, or the pseudo-type void, followed bya
'.' and the token class. The type ofC.class
, where C is the name of a class, interface, or array type isClass<C>
.http://docs.oracle.com/javase/specs/jls/se7/jls7.pdf
The big difference is when they need it. Since
Class.forName
accepts a string, the class name can be determined at runtime. Whereas of course,MyClass.class
is determined at compile-time. This makesClass.forName
useful for dynamically loading classes based on configuration (for instance, loading database drivers depending on the settings of a config file).Rounding things out:
obj.getClass()
is useful because you may not know the actual class of an object — for instance, in a method where you accept an argument using an interface, rather than class, such as infoo(Map m)
. You don't know the class ofm
, just that it's something that implementsMap
. (And 99% of the time, you shouldn't care what its class is, but that 1% crops up occasionally.)One important difference is: A.class will perform loading and linking of class A. Class.forName("A") will perform loading, linking and initialization of class A.
forName is a static method of class "Class". we require to provide the fully qualified name of the desired class. this can be used when name of class will come to known at runtime.
.class is not a method it is a keyword and can be used with primitive type like int. when Name of Class is known in advance & it is added to project, that time we use ClassName.class