Difference between MyClass.class and Class.forName

2020-03-03 03:43发布

问题:

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.

回答1:

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



回答2:

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.)



回答3:

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.



回答4:

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