Difference between MyClass.class and Class.forName(“className”)

前端 未结 4 462
Happy的楠姐
Happy的楠姐 2021-01-05 07:25

We can get class Class object by 3 methods:

  • MyClass.class
  • obj.getClass
  • Class.forName(\"className\")

I don\'t understood the di

4条回答
  •  我在风中等你
    2021-01-05 08:02

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

提交回复
热议问题