Difference between MyClass.class and Class.forName

2020-03-03 03:53发布

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.

4条回答
Rolldiameter
2楼-- · 2020-03-03 04:29
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

查看更多
一纸荒年 Trace。
3楼-- · 2020-03-03 04:30

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

查看更多
做个烂人
4楼-- · 2020-03-03 04:35

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.

查看更多
等我变得足够好
5楼-- · 2020-03-03 04:37
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

查看更多
登录 后发表回答