Reputation: 99
Class.forName("org.MyClass")
and MyClass.class
both require class name. So, what does it mean when we say Class.forName("org.MyClass")
is used when we don't know the name of the class at compile time and MyClass.class
is used when we know the name of the class?
How are these different from obj.getClass()
?
Upvotes: 1
Views: 171
Reputation: 117675
MyClass.class
:
Class<MyClass>
, hence newInstance()
returns MyClass
.Class.forName("org.MyClass")
:
Class<MyClass>
, but Class<?>
instead, hence newInstance()
returns Object
.ClassNotFoundException
which needs to be handled.Upvotes: 0
Reputation: 10249
with MyClass.class
you get the class at compile-time.
and with Class.forName("org.MyClass")
at runtime.
Your normaly pass a value to Class#forName and don't hardcode the String. If it's hard-coded, uses .class
Upvotes: 0
Reputation: 3115
Class.forName("org.MyClass") equal to MyClass
MyClass.class equal to Class<MyClass>
Upvotes: 0
Reputation: 206996
You already gave the answer yourself: when you use MyClass.class
, then the compiler needs to know what MyClass
is, so you'll need to have MyClass
in your classpath at compile time; whereas when you use Class.forName("org.MyClass")
, the class does not need to be in the classpath at compile time - only at runtime.
This is used for example for JDBC drivers. You write your code to use the JDBC API, but you don't need to specify at compile time which JDBC driver you're going to use. This also allows you to switch to another JDBC driver without recompiling your own code.
obj.getClass()
gets the Class
object for obj
.
Upvotes: 1
Reputation: 41281
MyClass.class
is generally known at compile time to be a given class.
obj.getClass()
is used when an object is known but not its class, or if the object is a refiable generic type, to get a class.
Class.forName("org.YourClass")
is needed if you know the name of the class (i.e. the name was passed over the network or was otherwise obtained as a string) without an instance of the class, or the class's identity known at compile-time.
Upvotes: 4