UserInteractive
UserInteractive

Reputation: 99

Class.forName("org.MyClass") and MyClass.class differences

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

Answers (5)

Eng.Fouad
Eng.Fouad

Reputation: 117675

MyClass.class:

  • Can be assigned to Class<MyClass>, hence newInstance() returns MyClass.
  • Compilation fails if the class doesn't exist in the classpath.
  • Doesn't throw any checked exceptions.

Class.forName("org.MyClass"):

  • Cannot be assigned to Class<MyClass>, but Class<?> instead, hence newInstance() returns Object.
  • Compilation successes even if the class doesn't exist in the classpath.
  • Throws the checked exception ClassNotFoundException which needs to be handled.

Upvotes: 0

Philipp Sander
Philipp Sander

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

subash
subash

Reputation: 3115

Class.forName("org.MyClass") equal to MyClass

MyClass.class equal to Class<MyClass>

Upvotes: 0

Jesper
Jesper

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

nanofarad
nanofarad

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

Related Questions