• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Class.forName

 
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What is the difference between Class.forName and
Class obj1 = new Class()
 
Ranch Hand
Posts: 226
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You can't call Class() or any other constructor on Class. All constructors for Class are private.
 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
reply
    Bookmark Topic Watch Topic
  • New Topic