Neal
Neal

Reputation: 73

Difference between MyClass.class and Class.forName("className")

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.

Upvotes: 7

Views: 4511

Answers (4)

javdev
javdev

Reputation: 904

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.

Upvotes: 2

amicngh
amicngh

Reputation: 7899

Class.forName("className"); 

It dynamically load the class based on fully qualified class name string.

obj.getClass

Returns the java.lang.Class object that represents the runtime class of the object.

MyClass.class:

A class literal is an expression consisting of the name of a class, interface, array, or primitive type, or the pseudo-type void, followed by a'.' and the token class. The type of C.class, where C is the name of a class, interface, or array type is Class<C>.

http://docs.oracle.com/javase/specs/jls/se7/jls7.pdf

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1073968

I don't understood the difference between: MyClass.class and Class.forName("className").

Because both will need Class Name.

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 makes Class.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 in foo(Map m). You don't know the class of m, just that it's something that implements Map. (And 99% of the time, you shouldn't care what its class is, but that 1% crops up occasionally.)

Upvotes: 8

swapy
swapy

Reputation: 1616

Class.forName("className"); 

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.

ClassName.class;

.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

Upvotes: 11

Related Questions