Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Class.forName  RSS feed

 
Glenny Dsilva
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the difference between Class.forName and
Class obj1 = new Class()
 
Timmy Marks
Ranch Hand
Posts: 226
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can't call Class() or any other constructor on Class. All constructors for Class are private.
 
Aman Verma
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Class.forName() is used to load the classes in JVM dynamically. It will return the instance of that class by default.
but MyClass class = new MyClass() will create a instance of MyClass only. Before creating instance of MyClass it should be loaded into JVM using import.
good stuff related to dynamic loading of classes can be found here
dynamic class loading
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"dynamic" is the key word above. With

class.forName( string ).newInstance();

we can create instances of classes that are not known at compile time. I use this trick all the time to add functionality to a system without having to change the core classes. I pass in a new classname in a string and it creates an instance and uses it.

Note that this code requires the instance to implement MyInterface. If I mess up and pass the name of a class that does not implement MyInterface, this will throw a cast exception.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!